xref: /netbsd-src/usr.bin/make/var.c (revision bbde328be4e75ea9ad02e9715ea13ca54b797ada)
1 /*	$NetBSD: var.c,v 1.158 2010/04/21 04:25:27 sjg Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
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.
21  *
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.
33  */
34 
35 /*
36  * Copyright (c) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
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.
57  *
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.
69  */
70 
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: var.c,v 1.158 2010/04/21 04:25:27 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.158 2010/04/21 04:25:27 sjg Exp $");
80 #endif
81 #endif /* not lint */
82 #endif
83 
84 /*-
85  * var.c --
86  *	Variable-handling functions
87  *
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.
93  *
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.
99  *
100  *	Var_Exists	    See if a variable exists.
101  *
102  *	Var_Value 	    Return the value of a variable in a context or
103  *			    NULL if the variable is undefined.
104  *
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.
110  *
111  *	Var_Parse 	    Parse a variable expansion from a string and
112  *			    return the result and the number of characters
113  *			    consumed.
114  *
115  *	Var_Delete	    Delete a variable in a context.
116  *
117  *	Var_Init  	    Initialize this module.
118  *
119  * Debugging:
120  *	Var_Dump  	    Print out all variables defined in the given
121  *			    context.
122  *
123  * XXX: There's a lot of duplication in these functions.
124  */
125 
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 
135 #include    "make.h"
136 #include    "buf.h"
137 #include    "dir.h"
138 #include    "job.h"
139 
140 /*
141  * This is a harmless return value for Var_Parse that can be used by Var_Subst
142  * to determine if there was an error in parsing -- easier than returning
143  * a flag, as things outside this module don't give a hoot.
144  */
145 char 	var_Error[] = "";
146 
147 /*
148  * Similar to var_Error, but returned when the 'errnum' flag for Var_Parse is
149  * set false. Why not just use a constant? Well, gcc likes to condense
150  * identical string instances...
151  */
152 static char	varNoError[] = "";
153 
154 /*
155  * Internally, variables are contained in four different contexts.
156  *	1) the environment. They may not be changed. If an environment
157  *	    variable is appended-to, the result is placed in the global
158  *	    context.
159  *	2) the global context. Variables set in the Makefile are located in
160  *	    the global context. It is the penultimate context searched when
161  *	    substituting.
162  *	3) the command-line context. All variables set on the command line
163  *	   are placed in this context. They are UNALTERABLE once placed here.
164  *	4) the local context. Each target has associated with it a context
165  *	   list. On this list are located the structures describing such
166  *	   local variables as $(@) and $(*)
167  * The four contexts are searched in the reverse order from which they are
168  * listed.
169  */
170 GNode          *VAR_GLOBAL;   /* variables from the makefile */
171 GNode          *VAR_CMD;      /* variables defined on the command-line */
172 
173 #define FIND_CMD	0x1   /* look in VAR_CMD when searching */
174 #define FIND_GLOBAL	0x2   /* look in VAR_GLOBAL as well */
175 #define FIND_ENV  	0x4   /* look in the environment also */
176 
177 typedef struct Var {
178     char          *name;	/* the variable's name */
179     Buffer	  val;		/* its value */
180     int		  flags;    	/* miscellaneous status flags */
181 #define VAR_IN_USE	1   	    /* Variable's value currently being used.
182 				     * Used to avoid recursion */
183 #define VAR_FROM_ENV	2   	    /* Variable comes from the environment */
184 #define VAR_JUNK  	4   	    /* Variable is a junk variable that
185 				     * should be destroyed when done with
186 				     * it. Used by Var_Parse for undefined,
187 				     * modified variables */
188 #define VAR_KEEP	8	    /* Variable is VAR_JUNK, but we found
189 				     * a use for it in some modifier and
190 				     * the value is therefore valid */
191 #define VAR_EXPORTED	16 	    /* Variable is exported */
192 #define VAR_REEXPORT	32	    /* Indicate if var needs re-export.
193 				     * This would be true if it contains $'s
194 				     */
195 #define VAR_FROM_CMD	64 	    /* Variable came from command line */
196 }  Var;
197 
198 /*
199  * Exporting vars is expensive so skip it if we can
200  */
201 #define VAR_EXPORTED_NONE	0
202 #define VAR_EXPORTED_YES	1
203 #define VAR_EXPORTED_ALL	2
204 static int var_exportedVars = VAR_EXPORTED_NONE;
205 /*
206  * We pass this to Var_Export when doing the initial export
207  * or after updating an exported var.
208  */
209 #define VAR_EXPORT_PARENT 1
210 
211 /* Var*Pattern flags */
212 #define VAR_SUB_GLOBAL	0x01	/* Apply substitution globally */
213 #define VAR_SUB_ONE	0x02	/* Apply substitution to one word */
214 #define VAR_SUB_MATCHED	0x04	/* There was a match */
215 #define VAR_MATCH_START	0x08	/* Match at start of word */
216 #define VAR_MATCH_END	0x10	/* Match at end of word */
217 #define VAR_NOSUBST	0x20	/* don't expand vars in VarGetPattern */
218 
219 /* Var_Set flags */
220 #define VAR_NO_EXPORT	0x01	/* do not export */
221 
222 typedef struct {
223     /*
224      * The following fields are set by Var_Parse() when it
225      * encounters modifiers that need to keep state for use by
226      * subsequent modifiers within the same variable expansion.
227      */
228     Byte	varSpace;	/* Word separator in expansions */
229     Boolean	oneBigWord;	/* TRUE if we will treat the variable as a
230 				 * single big word, even if it contains
231 				 * embedded spaces (as opposed to the
232 				 * usual behaviour of treating it as
233 				 * several space-separated words). */
234 } Var_Parse_State;
235 
236 /* struct passed as 'void *' to VarSubstitute() for ":S/lhs/rhs/",
237  * to VarSYSVMatch() for ":lhs=rhs". */
238 typedef struct {
239     const char   *lhs;	    /* String to match */
240     int		  leftLen; /* Length of string */
241     const char   *rhs;	    /* Replacement string (w/ &'s removed) */
242     int		  rightLen; /* Length of replacement */
243     int		  flags;
244 } VarPattern;
245 
246 /* struct passed as 'void *' to VarLoopExpand() for ":@tvar@str@" */
247 typedef struct {
248     GNode	*ctxt;		/* variable context */
249     char	*tvar;		/* name of temp var */
250     int		tvarLen;
251     char	*str;		/* string to expand */
252     int		strLen;
253     int		errnum;		/* errnum for not defined */
254 } VarLoop_t;
255 
256 #ifndef NO_REGEX
257 /* struct passed as 'void *' to VarRESubstitute() for ":C///" */
258 typedef struct {
259     regex_t	   re;
260     int		   nsub;
261     regmatch_t 	  *matches;
262     char 	  *replace;
263     int		   flags;
264 } VarREPattern;
265 #endif
266 
267 /* struct passed to VarSelectWords() for ":[start..end]" */
268 typedef struct {
269     int		start;		/* first word to select */
270     int		end;		/* last word to select */
271 } VarSelectWords_t;
272 
273 static Var *VarFind(const char *, GNode *, int);
274 static void VarAdd(const char *, const char *, GNode *);
275 static Boolean VarHead(GNode *, Var_Parse_State *,
276 			char *, Boolean, Buffer *, void *);
277 static Boolean VarTail(GNode *, Var_Parse_State *,
278 			char *, Boolean, Buffer *, void *);
279 static Boolean VarSuffix(GNode *, Var_Parse_State *,
280 			char *, Boolean, Buffer *, void *);
281 static Boolean VarRoot(GNode *, Var_Parse_State *,
282 			char *, Boolean, Buffer *, void *);
283 static Boolean VarMatch(GNode *, Var_Parse_State *,
284 			char *, Boolean, Buffer *, void *);
285 #ifdef SYSVVARSUB
286 static Boolean VarSYSVMatch(GNode *, Var_Parse_State *,
287 			char *, Boolean, Buffer *, void *);
288 #endif
289 static Boolean VarNoMatch(GNode *, Var_Parse_State *,
290 			char *, Boolean, Buffer *, void *);
291 #ifndef NO_REGEX
292 static void VarREError(int, regex_t *, const char *);
293 static Boolean VarRESubstitute(GNode *, Var_Parse_State *,
294 			char *, Boolean, Buffer *, void *);
295 #endif
296 static Boolean VarSubstitute(GNode *, Var_Parse_State *,
297 			char *, Boolean, Buffer *, void *);
298 static Boolean VarLoopExpand(GNode *, Var_Parse_State *,
299 			char *, Boolean, Buffer *, void *);
300 static char *VarGetPattern(GNode *, Var_Parse_State *,
301 			   int, const char **, int, int *, int *,
302 			   VarPattern *);
303 static char *VarQuote(char *);
304 static char *VarChangeCase(char *, int);
305 static char *VarModify(GNode *, Var_Parse_State *,
306     const char *,
307     Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *),
308     void *);
309 static char *VarOrder(const char *, const char);
310 static char *VarUniq(const char *);
311 static int VarWordCompare(const void *, const void *);
312 static void VarPrintVar(void *);
313 
314 #define BROPEN	'{'
315 #define BRCLOSE	'}'
316 #define PROPEN	'('
317 #define PRCLOSE	')'
318 
319 /*-
320  *-----------------------------------------------------------------------
321  * VarFind --
322  *	Find the given variable in the given context and any other contexts
323  *	indicated.
324  *
325  * Input:
326  *	name		name to find
327  *	ctxt		context in which to find it
328  *	flags		FIND_GLOBAL set means to look in the
329  *			VAR_GLOBAL context as well. FIND_CMD set means
330  *			to look in the VAR_CMD context also. FIND_ENV
331  *			set means to look in the environment
332  *
333  * Results:
334  *	A pointer to the structure describing the desired variable or
335  *	NULL if the variable does not exist.
336  *
337  * Side Effects:
338  *	None
339  *-----------------------------------------------------------------------
340  */
341 static Var *
342 VarFind(const char *name, GNode *ctxt, int flags)
343 {
344     Hash_Entry         	*var;
345     Var			*v;
346 
347 	/*
348 	 * If the variable name begins with a '.', it could very well be one of
349 	 * the local ones.  We check the name against all the local variables
350 	 * and substitute the short version in for 'name' if it matches one of
351 	 * them.
352 	 */
353 	if (*name == '.' && isupper((unsigned char) name[1]))
354 		switch (name[1]) {
355 		case 'A':
356 			if (!strcmp(name, ".ALLSRC"))
357 				name = ALLSRC;
358 			if (!strcmp(name, ".ARCHIVE"))
359 				name = ARCHIVE;
360 			break;
361 		case 'I':
362 			if (!strcmp(name, ".IMPSRC"))
363 				name = IMPSRC;
364 			break;
365 		case 'M':
366 			if (!strcmp(name, ".MEMBER"))
367 				name = MEMBER;
368 			break;
369 		case 'O':
370 			if (!strcmp(name, ".OODATE"))
371 				name = OODATE;
372 			break;
373 		case 'P':
374 			if (!strcmp(name, ".PREFIX"))
375 				name = PREFIX;
376 			break;
377 		case 'T':
378 			if (!strcmp(name, ".TARGET"))
379 				name = TARGET;
380 			break;
381 		}
382     /*
383      * First look for the variable in the given context. If it's not there,
384      * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
385      * depending on the FIND_* flags in 'flags'
386      */
387     var = Hash_FindEntry(&ctxt->context, name);
388 
389     if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
390 	var = Hash_FindEntry(&VAR_CMD->context, name);
391     }
392     if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
393 	(ctxt != VAR_GLOBAL))
394     {
395 	var = Hash_FindEntry(&VAR_GLOBAL->context, name);
396     }
397     if ((var == NULL) && (flags & FIND_ENV)) {
398 	char *env;
399 
400 	if ((env = getenv(name)) != NULL) {
401 	    int		len;
402 
403 	    v = bmake_malloc(sizeof(Var));
404 	    v->name = bmake_strdup(name);
405 
406 	    len = strlen(env);
407 
408 	    Buf_Init(&v->val, len + 1);
409 	    Buf_AddBytes(&v->val, len, env);
410 
411 	    v->flags = VAR_FROM_ENV;
412 	    return (v);
413 	} else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
414 		   (ctxt != VAR_GLOBAL))
415 	{
416 	    var = Hash_FindEntry(&VAR_GLOBAL->context, name);
417 	    if (var == NULL) {
418 		return NULL;
419 	    } else {
420 		return ((Var *)Hash_GetValue(var));
421 	    }
422 	} else {
423 	    return NULL;
424 	}
425     } else if (var == NULL) {
426 	return NULL;
427     } else {
428 	return ((Var *)Hash_GetValue(var));
429     }
430 }
431 
432 /*-
433  *-----------------------------------------------------------------------
434  * VarFreeEnv  --
435  *	If the variable is an environment variable, free it
436  *
437  * Input:
438  *	v		the variable
439  *	destroy		true if the value buffer should be destroyed.
440  *
441  * Results:
442  *	1 if it is an environment variable 0 ow.
443  *
444  * Side Effects:
445  *	The variable is free'ed if it is an environent variable.
446  *-----------------------------------------------------------------------
447  */
448 static Boolean
449 VarFreeEnv(Var *v, Boolean destroy)
450 {
451     if ((v->flags & VAR_FROM_ENV) == 0)
452 	return FALSE;
453     free(v->name);
454     Buf_Destroy(&v->val, destroy);
455     free(v);
456     return TRUE;
457 }
458 
459 /*-
460  *-----------------------------------------------------------------------
461  * VarAdd  --
462  *	Add a new variable of name name and value val to the given context
463  *
464  * Input:
465  *	name		name of variable to add
466  *	val		value to set it to
467  *	ctxt		context in which to set it
468  *
469  * Results:
470  *	None
471  *
472  * Side Effects:
473  *	The new variable is placed at the front of the given context
474  *	The name and val arguments are duplicated so they may
475  *	safely be freed.
476  *-----------------------------------------------------------------------
477  */
478 static void
479 VarAdd(const char *name, const char *val, GNode *ctxt)
480 {
481     Var   	  *v;
482     int		  len;
483     Hash_Entry    *h;
484 
485     v = bmake_malloc(sizeof(Var));
486 
487     len = val ? strlen(val) : 0;
488     Buf_Init(&v->val, len+1);
489     Buf_AddBytes(&v->val, len, val);
490 
491     v->flags = 0;
492 
493     h = Hash_CreateEntry(&ctxt->context, name, NULL);
494     Hash_SetValue(h, v);
495     v->name = h->name;
496     if (DEBUG(VAR)) {
497 	fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
498     }
499 }
500 
501 /*-
502  *-----------------------------------------------------------------------
503  * Var_Delete --
504  *	Remove a variable from a context.
505  *
506  * Results:
507  *	None.
508  *
509  * Side Effects:
510  *	The Var structure is removed and freed.
511  *
512  *-----------------------------------------------------------------------
513  */
514 void
515 Var_Delete(const char *name, GNode *ctxt)
516 {
517     Hash_Entry 	  *ln;
518 
519     ln = Hash_FindEntry(&ctxt->context, name);
520     if (DEBUG(VAR)) {
521 	fprintf(debug_file, "%s:delete %s%s\n",
522 	    ctxt->name, name, ln ? "" : " (not found)");
523     }
524     if (ln != NULL) {
525 	Var 	  *v;
526 
527 	v = (Var *)Hash_GetValue(ln);
528 	if ((v->flags & VAR_EXPORTED)) {
529 	    unsetenv(v->name);
530 	}
531 	if (strcmp(MAKE_EXPORTED, v->name) == 0) {
532 	    var_exportedVars = VAR_EXPORTED_NONE;
533 	}
534 	if (v->name != ln->name)
535 		free(v->name);
536 	Hash_DeleteEntry(&ctxt->context, ln);
537 	Buf_Destroy(&v->val, TRUE);
538 	free(v);
539     }
540 }
541 
542 
543 /*
544  * Export a var.
545  * We ignore make internal variables (those which start with '.')
546  * Also we jump through some hoops to avoid calling setenv
547  * more than necessary since it can leak.
548  * We only manipulate flags of vars if 'parent' is set.
549  */
550 static int
551 Var_Export1(const char *name, int parent)
552 {
553     char tmp[BUFSIZ];
554     Var *v;
555     char *val = NULL;
556     int n;
557 
558     if (*name == '.')
559 	return 0;			/* skip internals */
560     if (!name[1]) {
561 	/*
562 	 * A single char.
563 	 * If it is one of the vars that should only appear in
564 	 * local context, skip it, else we can get Var_Subst
565 	 * into a loop.
566 	 */
567 	switch (name[0]) {
568 	case '@':
569 	case '%':
570 	case '*':
571 	case '!':
572 	    return 0;
573 	}
574     }
575     v = VarFind(name, VAR_GLOBAL, 0);
576     if (v == NULL) {
577 	return 0;
578     }
579     if (!parent &&
580 	(v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
581 	return 0;			/* nothing to do */
582     }
583     val = Buf_GetAll(&v->val, NULL);
584     if (strchr(val, '$')) {
585 	if (parent) {
586 	    /*
587 	     * Flag this as something we need to re-export.
588 	     * No point actually exporting it now though,
589 	     * the child can do it at the last minute.
590 	     */
591 	    v->flags |= (VAR_EXPORTED|VAR_REEXPORT);
592 	    return 1;
593 	}
594 	if (v->flags & VAR_IN_USE) {
595 	    /*
596 	     * We recursed while exporting in a child.
597 	     * This isn't going to end well, just skip it.
598 	     */
599 	    return 0;
600 	}
601 	n = snprintf(tmp, sizeof(tmp), "${%s}", name);
602 	if (n < (int)sizeof(tmp)) {
603 	    val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
604 	    setenv(name, val, 1);
605 	    free(val);
606 	}
607     } else {
608 	if (parent) {
609 	    v->flags &= ~VAR_REEXPORT;	/* once will do */
610 	}
611 	if (parent || !(v->flags & VAR_EXPORTED)) {
612 	    setenv(name, val, 1);
613 	}
614     }
615     /*
616      * This is so Var_Set knows to call Var_Export again...
617      */
618     if (parent) {
619 	v->flags |= VAR_EXPORTED;
620     }
621     return 1;
622 }
623 
624 /*
625  * This gets called from our children.
626  */
627 void
628 Var_ExportVars(void)
629 {
630     char tmp[BUFSIZ];
631     Hash_Entry         	*var;
632     Hash_Search 	state;
633     Var *v;
634     char *val;
635     int n;
636 
637     if (VAR_EXPORTED_NONE == var_exportedVars)
638 	return;
639 
640     if (VAR_EXPORTED_ALL == var_exportedVars) {
641 	/*
642 	 * Ouch! This is crazy...
643 	 */
644 	for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state);
645 	     var != NULL;
646 	     var = Hash_EnumNext(&state)) {
647 	    v = (Var *)Hash_GetValue(var);
648 	    Var_Export1(v->name, 0);
649 	}
650 	return;
651     }
652     /*
653      * We have a number of exported vars,
654      */
655     n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
656     if (n < (int)sizeof(tmp)) {
657 	char **av;
658 	char *as;
659 	int ac;
660 	int i;
661 
662 	val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
663 	av = brk_string(val, &ac, FALSE, &as);
664 	for (i = 0; i < ac; i++) {
665 	    Var_Export1(av[i], 0);
666 	}
667 	free(val);
668 	free(as);
669 	free(av);
670     }
671 }
672 
673 /*
674  * This is called when .export is seen or
675  * .MAKE.EXPORTED is modified.
676  * It is also called when any exported var is modified.
677  */
678 void
679 Var_Export(char *str, int isExport)
680 {
681     char *name;
682     char *val;
683     char **av;
684     char *as;
685     int ac;
686     int i;
687 
688     if (isExport && (!str || !str[0])) {
689 	var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
690 	return;
691     }
692 
693     val = Var_Subst(NULL, str, VAR_GLOBAL, 0);
694     av = brk_string(val, &ac, FALSE, &as);
695     for (i = 0; i < ac; i++) {
696 	name = av[i];
697 	if (!name[1]) {
698 	    /*
699 	     * A single char.
700 	     * If it is one of the vars that should only appear in
701 	     * local context, skip it, else we can get Var_Subst
702 	     * into a loop.
703 	     */
704 	    switch (name[0]) {
705 	    case '@':
706 	    case '%':
707 	    case '*':
708 	    case '!':
709 		continue;
710 	    }
711 	}
712 	if (Var_Export1(name, VAR_EXPORT_PARENT)) {
713 	    if (VAR_EXPORTED_ALL != var_exportedVars)
714 		var_exportedVars = VAR_EXPORTED_YES;
715 	    if (isExport) {
716 		Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
717 	    }
718 	}
719     }
720     free(val);
721     free(as);
722     free(av);
723 }
724 
725 
726 /*
727  * This is called when .unexport[-env] is seen.
728  */
729 void
730 Var_UnExport(char *str)
731 {
732     char tmp[BUFSIZ];
733     char *vlist;
734     char *cp;
735     Boolean unexport_env;
736     int n;
737 
738     if (!str || !str[0]) {
739 	return; 			/* assert? */
740     }
741 
742     vlist = NULL;
743 
744     str += 8;
745     unexport_env = (strncmp(str, "-env", 4) == 0);
746     if (unexport_env) {
747 	extern char **environ;
748 	static char **savenv;
749 	char **newenv;
750 
751 	cp = getenv(MAKE_LEVEL);	/* we should preserve this */
752 	if (environ == savenv) {
753 	    /* we have been here before! */
754 	    newenv = bmake_realloc(environ, 2 * sizeof(char *));
755 	} else {
756 	    if (savenv) {
757 		free(savenv);
758 		savenv = NULL;
759 	    }
760 	    newenv = bmake_malloc(2 * sizeof(char *));
761 	}
762 	if (!newenv)
763 	    return;
764 	/* Note: we cannot safely free() the original environ. */
765 	environ = savenv = newenv;
766 	newenv[0] = NULL;
767 	newenv[1] = NULL;
768 	setenv(MAKE_LEVEL, cp, 1);
769     } else {
770 	for (; *str != '\n' && isspace((unsigned char) *str); str++)
771 	    continue;
772 	if (str[0] && str[0] != '\n') {
773 	    vlist = str;
774 	}
775     }
776 
777     if (!vlist) {
778 	/* Using .MAKE.EXPORTED */
779 	n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
780 	if (n < (int)sizeof(tmp)) {
781 	    vlist = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
782 	}
783     }
784     if (vlist) {
785 	Var *v;
786 	char **av;
787 	char *as;
788 	int ac;
789 	int i;
790 
791 	av = brk_string(vlist, &ac, FALSE, &as);
792 	for (i = 0; i < ac; i++) {
793 	    v = VarFind(av[i], VAR_GLOBAL, 0);
794 	    if (!v)
795 		continue;
796 	    if (!unexport_env &&
797 		(v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
798 		unsetenv(v->name);
799 	    }
800 	    v->flags &= ~(VAR_EXPORTED|VAR_REEXPORT);
801 	    /*
802 	     * If we are unexporting a list,
803 	     * remove each one from .MAKE.EXPORTED.
804 	     * If we are removing them all,
805 	     * just delete .MAKE.EXPORTED below.
806 	     */
807 	    if (vlist == str) {
808 		n = snprintf(tmp, sizeof(tmp),
809 			     "${" MAKE_EXPORTED ":N%s}", v->name);
810 		if (n < (int)sizeof(tmp)) {
811 		    cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
812 		    Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL, 0);
813 		    free(cp);
814 		}
815 	    }
816 	}
817 	free(as);
818 	free(av);
819 	if (vlist != str) {
820 	    Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
821 	    free(vlist);
822 	}
823     }
824 }
825 
826 /*-
827  *-----------------------------------------------------------------------
828  * Var_Set --
829  *	Set the variable name to the value val in the given context.
830  *
831  * Input:
832  *	name		name of variable to set
833  *	val		value to give to the variable
834  *	ctxt		context in which to set it
835  *
836  * Results:
837  *	None.
838  *
839  * Side Effects:
840  *	If the variable doesn't yet exist, a new record is created for it.
841  *	Else the old value is freed and the new one stuck in its place
842  *
843  * Notes:
844  *	The variable is searched for only in its context before being
845  *	created in that context. I.e. if the context is VAR_GLOBAL,
846  *	only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
847  *	VAR_CMD->context is searched. This is done to avoid the literally
848  *	thousands of unnecessary strcmp's that used to be done to
849  *	set, say, $(@) or $(<).
850  *	If the context is VAR_GLOBAL though, we check if the variable
851  *	was set in VAR_CMD from the command line and skip it if so.
852  *-----------------------------------------------------------------------
853  */
854 void
855 Var_Set(const char *name, const char *val, GNode *ctxt, int flags)
856 {
857     Var   *v;
858     char *expanded_name = NULL;
859 
860     /*
861      * We only look for a variable in the given context since anything set
862      * here will override anything in a lower context, so there's not much
863      * point in searching them all just to save a bit of memory...
864      */
865     if (strchr(name, '$') != NULL) {
866 	expanded_name = Var_Subst(NULL, name, ctxt, 0);
867 	if (expanded_name[0] == 0) {
868 	    if (DEBUG(VAR)) {
869 		fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
870 			"name expands to empty string - ignored\n",
871 			name, val);
872 	    }
873 	    free(expanded_name);
874 	    return;
875 	}
876 	name = expanded_name;
877     }
878     if (ctxt == VAR_GLOBAL) {
879 	v = VarFind(name, VAR_CMD, 0);
880 	if (v != NULL) {
881 	    if ((v->flags & VAR_FROM_CMD)) {
882 		if (DEBUG(VAR)) {
883 		    fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
884 		}
885 		goto out;
886 	    }
887 	    VarFreeEnv(v, TRUE);
888 	}
889     }
890     v = VarFind(name, ctxt, 0);
891     if (v == NULL) {
892 	VarAdd(name, val, ctxt);
893     } else {
894 	Buf_Empty(&v->val);
895 	Buf_AddBytes(&v->val, strlen(val), val);
896 
897 	if (DEBUG(VAR)) {
898 	    fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
899 	}
900 	if ((v->flags & VAR_EXPORTED)) {
901 	    Var_Export1(name, VAR_EXPORT_PARENT);
902 	}
903     }
904     /*
905      * Any variables given on the command line are automatically exported
906      * to the environment (as per POSIX standard)
907      */
908     if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
909 	if (v == NULL) {
910 	    /* we just added it */
911 	    v = VarFind(name, ctxt, 0);
912 	}
913 	if (v != NULL)
914 	    v->flags |= VAR_FROM_CMD;
915 	/*
916 	 * If requested, don't export these in the environment
917 	 * individually.  We still put them in MAKEOVERRIDES so
918 	 * that the command-line settings continue to override
919 	 * Makefile settings.
920 	 */
921 	if (varNoExportEnv != TRUE)
922 	    setenv(name, val, 1);
923 
924 	Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
925     }
926     /*
927      * Another special case.
928      * Several make's support this sort of mechanism for tracking
929      * recursion - but each uses a different name.
930      * We allow the makefiles to update .MAKE.LEVEL and ensure
931      * children see a correctly incremented value.
932      */
933     if (ctxt == VAR_GLOBAL && strcmp(MAKE_LEVEL, name) == 0) {
934 	char tmp[64];
935 	int level;
936 
937 	level = atoi(val);
938 	snprintf(tmp, sizeof(tmp), "%u", level + 1);
939 	setenv(MAKE_LEVEL, tmp, 1);
940     }
941 
942 
943  out:
944     if (expanded_name != NULL)
945 	free(expanded_name);
946     if (v != NULL)
947 	VarFreeEnv(v, TRUE);
948 }
949 
950 /*-
951  *-----------------------------------------------------------------------
952  * Var_Append --
953  *	The variable of the given name has the given value appended to it in
954  *	the given context.
955  *
956  * Input:
957  *	name		name of variable to modify
958  *	val		String to append to it
959  *	ctxt		Context in which this should occur
960  *
961  * Results:
962  *	None
963  *
964  * Side Effects:
965  *	If the variable doesn't exist, it is created. Else the strings
966  *	are concatenated (with a space in between).
967  *
968  * Notes:
969  *	Only if the variable is being sought in the global context is the
970  *	environment searched.
971  *	XXX: Knows its calling circumstances in that if called with ctxt
972  *	an actual target, it will only search that context since only
973  *	a local variable could be being appended to. This is actually
974  *	a big win and must be tolerated.
975  *-----------------------------------------------------------------------
976  */
977 void
978 Var_Append(const char *name, const char *val, GNode *ctxt)
979 {
980     Var		   *v;
981     Hash_Entry	   *h;
982     char *expanded_name = NULL;
983 
984     if (strchr(name, '$') != NULL) {
985 	expanded_name = Var_Subst(NULL, name, ctxt, 0);
986 	if (expanded_name[0] == 0) {
987 	    if (DEBUG(VAR)) {
988 		fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
989 			"name expands to empty string - ignored\n",
990 			name, val);
991 	    }
992 	    free(expanded_name);
993 	    return;
994 	}
995 	name = expanded_name;
996     }
997 
998     v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
999 
1000     if (v == NULL) {
1001 	VarAdd(name, val, ctxt);
1002     } else {
1003 	Buf_AddByte(&v->val, ' ');
1004 	Buf_AddBytes(&v->val, strlen(val), val);
1005 
1006 	if (DEBUG(VAR)) {
1007 	    fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
1008 		   Buf_GetAll(&v->val, NULL));
1009 	}
1010 
1011 	if (v->flags & VAR_FROM_ENV) {
1012 	    /*
1013 	     * If the original variable came from the environment, we
1014 	     * have to install it in the global context (we could place
1015 	     * it in the environment, but then we should provide a way to
1016 	     * export other variables...)
1017 	     */
1018 	    v->flags &= ~VAR_FROM_ENV;
1019 	    h = Hash_CreateEntry(&ctxt->context, name, NULL);
1020 	    Hash_SetValue(h, v);
1021 	}
1022     }
1023     if (expanded_name != NULL)
1024 	free(expanded_name);
1025 }
1026 
1027 /*-
1028  *-----------------------------------------------------------------------
1029  * Var_Exists --
1030  *	See if the given variable exists.
1031  *
1032  * Input:
1033  *	name		Variable to find
1034  *	ctxt		Context in which to start search
1035  *
1036  * Results:
1037  *	TRUE if it does, FALSE if it doesn't
1038  *
1039  * Side Effects:
1040  *	None.
1041  *
1042  *-----------------------------------------------------------------------
1043  */
1044 Boolean
1045 Var_Exists(const char *name, GNode *ctxt)
1046 {
1047     Var		  *v;
1048     char          *cp;
1049 
1050     if ((cp = strchr(name, '$')) != NULL) {
1051 	cp = Var_Subst(NULL, name, ctxt, FALSE);
1052     }
1053     v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
1054     if (cp != NULL) {
1055 	free(cp);
1056     }
1057     if (v == NULL) {
1058 	return(FALSE);
1059     } else {
1060 	(void)VarFreeEnv(v, TRUE);
1061     }
1062     return(TRUE);
1063 }
1064 
1065 /*-
1066  *-----------------------------------------------------------------------
1067  * Var_Value --
1068  *	Return the value of the named variable in the given context
1069  *
1070  * Input:
1071  *	name		name to find
1072  *	ctxt		context in which to search for it
1073  *
1074  * Results:
1075  *	The value if the variable exists, NULL if it doesn't
1076  *
1077  * Side Effects:
1078  *	None
1079  *-----------------------------------------------------------------------
1080  */
1081 char *
1082 Var_Value(const char *name, GNode *ctxt, char **frp)
1083 {
1084     Var            *v;
1085 
1086     v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1087     *frp = NULL;
1088     if (v != NULL) {
1089 	char *p = (Buf_GetAll(&v->val, NULL));
1090 	if (VarFreeEnv(v, FALSE))
1091 	    *frp = p;
1092 	return p;
1093     } else {
1094 	return NULL;
1095     }
1096 }
1097 
1098 /*-
1099  *-----------------------------------------------------------------------
1100  * VarHead --
1101  *	Remove the tail of the given word and place the result in the given
1102  *	buffer.
1103  *
1104  * Input:
1105  *	word		Word to trim
1106  *	addSpace	True if need to add a space to the buffer
1107  *			before sticking in the head
1108  *	buf		Buffer in which to store it
1109  *
1110  * Results:
1111  *	TRUE if characters were added to the buffer (a space needs to be
1112  *	added to the buffer before the next word).
1113  *
1114  * Side Effects:
1115  *	The trimmed word is added to the buffer.
1116  *
1117  *-----------------------------------------------------------------------
1118  */
1119 static Boolean
1120 VarHead(GNode *ctx __unused, Var_Parse_State *vpstate,
1121 	char *word, Boolean addSpace, Buffer *buf,
1122 	void *dummy)
1123 {
1124     char *slash;
1125 
1126     slash = strrchr(word, '/');
1127     if (slash != NULL) {
1128 	if (addSpace && vpstate->varSpace) {
1129 	    Buf_AddByte(buf, vpstate->varSpace);
1130 	}
1131 	*slash = '\0';
1132 	Buf_AddBytes(buf, strlen(word), word);
1133 	*slash = '/';
1134 	return (TRUE);
1135     } else {
1136 	/*
1137 	 * If no directory part, give . (q.v. the POSIX standard)
1138 	 */
1139 	if (addSpace && vpstate->varSpace)
1140 	    Buf_AddByte(buf, vpstate->varSpace);
1141 	Buf_AddByte(buf, '.');
1142     }
1143     return(dummy ? TRUE : TRUE);
1144 }
1145 
1146 /*-
1147  *-----------------------------------------------------------------------
1148  * VarTail --
1149  *	Remove the head of the given word and place the result in the given
1150  *	buffer.
1151  *
1152  * Input:
1153  *	word		Word to trim
1154  *	addSpace	True if need to add a space to the buffer
1155  *			before adding the tail
1156  *	buf		Buffer in which to store it
1157  *
1158  * Results:
1159  *	TRUE if characters were added to the buffer (a space needs to be
1160  *	added to the buffer before the next word).
1161  *
1162  * Side Effects:
1163  *	The trimmed word is added to the buffer.
1164  *
1165  *-----------------------------------------------------------------------
1166  */
1167 static Boolean
1168 VarTail(GNode *ctx __unused, Var_Parse_State *vpstate,
1169 	char *word, Boolean addSpace, Buffer *buf,
1170 	void *dummy)
1171 {
1172     char *slash;
1173 
1174     if (addSpace && vpstate->varSpace) {
1175 	Buf_AddByte(buf, vpstate->varSpace);
1176     }
1177 
1178     slash = strrchr(word, '/');
1179     if (slash != NULL) {
1180 	*slash++ = '\0';
1181 	Buf_AddBytes(buf, strlen(slash), slash);
1182 	slash[-1] = '/';
1183     } else {
1184 	Buf_AddBytes(buf, strlen(word), word);
1185     }
1186     return (dummy ? TRUE : TRUE);
1187 }
1188 
1189 /*-
1190  *-----------------------------------------------------------------------
1191  * VarSuffix --
1192  *	Place the suffix of the given word in the given buffer.
1193  *
1194  * Input:
1195  *	word		Word to trim
1196  *	addSpace	TRUE if need to add a space before placing the
1197  *			suffix in the buffer
1198  *	buf		Buffer in which to store it
1199  *
1200  * Results:
1201  *	TRUE if characters were added to the buffer (a space needs to be
1202  *	added to the buffer before the next word).
1203  *
1204  * Side Effects:
1205  *	The suffix from the word is placed in the buffer.
1206  *
1207  *-----------------------------------------------------------------------
1208  */
1209 static Boolean
1210 VarSuffix(GNode *ctx __unused, Var_Parse_State *vpstate,
1211 	  char *word, Boolean addSpace, Buffer *buf,
1212 	  void *dummy)
1213 {
1214     char *dot;
1215 
1216     dot = strrchr(word, '.');
1217     if (dot != NULL) {
1218 	if (addSpace && vpstate->varSpace) {
1219 	    Buf_AddByte(buf, vpstate->varSpace);
1220 	}
1221 	*dot++ = '\0';
1222 	Buf_AddBytes(buf, strlen(dot), dot);
1223 	dot[-1] = '.';
1224 	addSpace = TRUE;
1225     }
1226     return (dummy ? addSpace : addSpace);
1227 }
1228 
1229 /*-
1230  *-----------------------------------------------------------------------
1231  * VarRoot --
1232  *	Remove the suffix of the given word and place the result in the
1233  *	buffer.
1234  *
1235  * Input:
1236  *	word		Word to trim
1237  *	addSpace	TRUE if need to add a space to the buffer
1238  *			before placing the root in it
1239  *	buf		Buffer in which to store it
1240  *
1241  * Results:
1242  *	TRUE if characters were added to the buffer (a space needs to be
1243  *	added to the buffer before the next word).
1244  *
1245  * Side Effects:
1246  *	The trimmed word is added to the buffer.
1247  *
1248  *-----------------------------------------------------------------------
1249  */
1250 static Boolean
1251 VarRoot(GNode *ctx __unused, Var_Parse_State *vpstate,
1252 	char *word, Boolean addSpace, Buffer *buf,
1253 	void *dummy)
1254 {
1255     char *dot;
1256 
1257     if (addSpace && vpstate->varSpace) {
1258 	Buf_AddByte(buf, vpstate->varSpace);
1259     }
1260 
1261     dot = strrchr(word, '.');
1262     if (dot != NULL) {
1263 	*dot = '\0';
1264 	Buf_AddBytes(buf, strlen(word), word);
1265 	*dot = '.';
1266     } else {
1267 	Buf_AddBytes(buf, strlen(word), word);
1268     }
1269     return (dummy ? TRUE : TRUE);
1270 }
1271 
1272 /*-
1273  *-----------------------------------------------------------------------
1274  * VarMatch --
1275  *	Place the word in the buffer if it matches the given pattern.
1276  *	Callback function for VarModify to implement the :M modifier.
1277  *
1278  * Input:
1279  *	word		Word to examine
1280  *	addSpace	TRUE if need to add a space to the buffer
1281  *			before adding the word, if it matches
1282  *	buf		Buffer in which to store it
1283  *	pattern		Pattern the word must match
1284  *
1285  * Results:
1286  *	TRUE if a space should be placed in the buffer before the next
1287  *	word.
1288  *
1289  * Side Effects:
1290  *	The word may be copied to the buffer.
1291  *
1292  *-----------------------------------------------------------------------
1293  */
1294 static Boolean
1295 VarMatch(GNode *ctx __unused, Var_Parse_State *vpstate,
1296 	 char *word, Boolean addSpace, Buffer *buf,
1297 	 void *pattern)
1298 {
1299     if (DEBUG(VAR))
1300 	fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern);
1301     if (Str_Match(word, (char *)pattern)) {
1302 	if (addSpace && vpstate->varSpace) {
1303 	    Buf_AddByte(buf, vpstate->varSpace);
1304 	}
1305 	addSpace = TRUE;
1306 	Buf_AddBytes(buf, strlen(word), word);
1307     }
1308     return(addSpace);
1309 }
1310 
1311 #ifdef SYSVVARSUB
1312 /*-
1313  *-----------------------------------------------------------------------
1314  * VarSYSVMatch --
1315  *	Place the word in the buffer if it matches the given pattern.
1316  *	Callback function for VarModify to implement the System V %
1317  *	modifiers.
1318  *
1319  * Input:
1320  *	word		Word to examine
1321  *	addSpace	TRUE if need to add a space to the buffer
1322  *			before adding the word, if it matches
1323  *	buf		Buffer in which to store it
1324  *	patp		Pattern the word must match
1325  *
1326  * Results:
1327  *	TRUE if a space should be placed in the buffer before the next
1328  *	word.
1329  *
1330  * Side Effects:
1331  *	The word may be copied to the buffer.
1332  *
1333  *-----------------------------------------------------------------------
1334  */
1335 static Boolean
1336 VarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate,
1337 	     char *word, Boolean addSpace, Buffer *buf,
1338 	     void *patp)
1339 {
1340     int len;
1341     char *ptr;
1342     VarPattern 	  *pat = (VarPattern *)patp;
1343     char *varexp;
1344 
1345     if (addSpace && vpstate->varSpace)
1346 	Buf_AddByte(buf, vpstate->varSpace);
1347 
1348     addSpace = TRUE;
1349 
1350     if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
1351         varexp = Var_Subst(NULL, pat->rhs, ctx, 0);
1352 	Str_SYSVSubst(buf, varexp, ptr, len);
1353 	free(varexp);
1354     } else {
1355 	Buf_AddBytes(buf, strlen(word), word);
1356     }
1357 
1358     return(addSpace);
1359 }
1360 #endif
1361 
1362 
1363 /*-
1364  *-----------------------------------------------------------------------
1365  * VarNoMatch --
1366  *	Place the word in the buffer if it doesn't match the given pattern.
1367  *	Callback function for VarModify to implement the :N modifier.
1368  *
1369  * Input:
1370  *	word		Word to examine
1371  *	addSpace	TRUE if need to add a space to the buffer
1372  *			before adding the word, if it matches
1373  *	buf		Buffer in which to store it
1374  *	pattern		Pattern the word must match
1375  *
1376  * Results:
1377  *	TRUE if a space should be placed in the buffer before the next
1378  *	word.
1379  *
1380  * Side Effects:
1381  *	The word may be copied to the buffer.
1382  *
1383  *-----------------------------------------------------------------------
1384  */
1385 static Boolean
1386 VarNoMatch(GNode *ctx __unused, Var_Parse_State *vpstate,
1387 	   char *word, Boolean addSpace, Buffer *buf,
1388 	   void *pattern)
1389 {
1390     if (!Str_Match(word, (char *)pattern)) {
1391 	if (addSpace && vpstate->varSpace) {
1392 	    Buf_AddByte(buf, vpstate->varSpace);
1393 	}
1394 	addSpace = TRUE;
1395 	Buf_AddBytes(buf, strlen(word), word);
1396     }
1397     return(addSpace);
1398 }
1399 
1400 
1401 /*-
1402  *-----------------------------------------------------------------------
1403  * VarSubstitute --
1404  *	Perform a string-substitution on the given word, placing the
1405  *	result in the passed buffer.
1406  *
1407  * Input:
1408  *	word		Word to modify
1409  *	addSpace	True if space should be added before
1410  *			other characters
1411  *	buf		Buffer for result
1412  *	patternp	Pattern for substitution
1413  *
1414  * Results:
1415  *	TRUE if a space is needed before more characters are added.
1416  *
1417  * Side Effects:
1418  *	None.
1419  *
1420  *-----------------------------------------------------------------------
1421  */
1422 static Boolean
1423 VarSubstitute(GNode *ctx __unused, Var_Parse_State *vpstate,
1424 	      char *word, Boolean addSpace, Buffer *buf,
1425 	      void *patternp)
1426 {
1427     int  	wordLen;    /* Length of word */
1428     char 	*cp;	    /* General pointer */
1429     VarPattern	*pattern = (VarPattern *)patternp;
1430 
1431     wordLen = strlen(word);
1432     if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
1433 	(VAR_SUB_ONE|VAR_SUB_MATCHED)) {
1434 	/*
1435 	 * Still substituting -- break it down into simple anchored cases
1436 	 * and if none of them fits, perform the general substitution case.
1437 	 */
1438 	if ((pattern->flags & VAR_MATCH_START) &&
1439 	    (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
1440 		/*
1441 		 * Anchored at start and beginning of word matches pattern
1442 		 */
1443 		if ((pattern->flags & VAR_MATCH_END) &&
1444 		    (wordLen == pattern->leftLen)) {
1445 			/*
1446 			 * Also anchored at end and matches to the end (word
1447 			 * is same length as pattern) add space and rhs only
1448 			 * if rhs is non-null.
1449 			 */
1450 			if (pattern->rightLen != 0) {
1451 			    if (addSpace && vpstate->varSpace) {
1452 				Buf_AddByte(buf, vpstate->varSpace);
1453 			    }
1454 			    addSpace = TRUE;
1455 			    Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1456 			}
1457 			pattern->flags |= VAR_SUB_MATCHED;
1458 		} else if (pattern->flags & VAR_MATCH_END) {
1459 		    /*
1460 		     * Doesn't match to end -- copy word wholesale
1461 		     */
1462 		    goto nosub;
1463 		} else {
1464 		    /*
1465 		     * Matches at start but need to copy in trailing characters
1466 		     */
1467 		    if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
1468 			if (addSpace && vpstate->varSpace) {
1469 			    Buf_AddByte(buf, vpstate->varSpace);
1470 			}
1471 			addSpace = TRUE;
1472 		    }
1473 		    Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1474 		    Buf_AddBytes(buf, wordLen - pattern->leftLen,
1475 				 (word + pattern->leftLen));
1476 		    pattern->flags |= VAR_SUB_MATCHED;
1477 		}
1478 	} else if (pattern->flags & VAR_MATCH_START) {
1479 	    /*
1480 	     * Had to match at start of word and didn't -- copy whole word.
1481 	     */
1482 	    goto nosub;
1483 	} else if (pattern->flags & VAR_MATCH_END) {
1484 	    /*
1485 	     * Anchored at end, Find only place match could occur (leftLen
1486 	     * characters from the end of the word) and see if it does. Note
1487 	     * that because the $ will be left at the end of the lhs, we have
1488 	     * to use strncmp.
1489 	     */
1490 	    cp = word + (wordLen - pattern->leftLen);
1491 	    if ((cp >= word) &&
1492 		(strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
1493 		/*
1494 		 * Match found. If we will place characters in the buffer,
1495 		 * add a space before hand as indicated by addSpace, then
1496 		 * stuff in the initial, unmatched part of the word followed
1497 		 * by the right-hand-side.
1498 		 */
1499 		if (((cp - word) + pattern->rightLen) != 0) {
1500 		    if (addSpace && vpstate->varSpace) {
1501 			Buf_AddByte(buf, vpstate->varSpace);
1502 		    }
1503 		    addSpace = TRUE;
1504 		}
1505 		Buf_AddBytes(buf, cp - word, word);
1506 		Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1507 		pattern->flags |= VAR_SUB_MATCHED;
1508 	    } else {
1509 		/*
1510 		 * Had to match at end and didn't. Copy entire word.
1511 		 */
1512 		goto nosub;
1513 	    }
1514 	} else {
1515 	    /*
1516 	     * Pattern is unanchored: search for the pattern in the word using
1517 	     * String_FindSubstring, copying unmatched portions and the
1518 	     * right-hand-side for each match found, handling non-global
1519 	     * substitutions correctly, etc. When the loop is done, any
1520 	     * remaining part of the word (word and wordLen are adjusted
1521 	     * accordingly through the loop) is copied straight into the
1522 	     * buffer.
1523 	     * addSpace is set FALSE as soon as a space is added to the
1524 	     * buffer.
1525 	     */
1526 	    Boolean done;
1527 	    int origSize;
1528 
1529 	    done = FALSE;
1530 	    origSize = Buf_Size(buf);
1531 	    while (!done) {
1532 		cp = Str_FindSubstring(word, pattern->lhs);
1533 		if (cp != NULL) {
1534 		    if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1535 			Buf_AddByte(buf, vpstate->varSpace);
1536 			addSpace = FALSE;
1537 		    }
1538 		    Buf_AddBytes(buf, cp-word, word);
1539 		    Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1540 		    wordLen -= (cp - word) + pattern->leftLen;
1541 		    word = cp + pattern->leftLen;
1542 		    if (wordLen == 0) {
1543 			done = TRUE;
1544 		    }
1545 		    if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
1546 			done = TRUE;
1547 		    }
1548 		    pattern->flags |= VAR_SUB_MATCHED;
1549 		} else {
1550 		    done = TRUE;
1551 		}
1552 	    }
1553 	    if (wordLen != 0) {
1554 		if (addSpace && vpstate->varSpace) {
1555 		    Buf_AddByte(buf, vpstate->varSpace);
1556 		}
1557 		Buf_AddBytes(buf, wordLen, word);
1558 	    }
1559 	    /*
1560 	     * If added characters to the buffer, need to add a space
1561 	     * before we add any more. If we didn't add any, just return
1562 	     * the previous value of addSpace.
1563 	     */
1564 	    return ((Buf_Size(buf) != origSize) || addSpace);
1565 	}
1566 	return (addSpace);
1567     }
1568  nosub:
1569     if (addSpace && vpstate->varSpace) {
1570 	Buf_AddByte(buf, vpstate->varSpace);
1571     }
1572     Buf_AddBytes(buf, wordLen, word);
1573     return(TRUE);
1574 }
1575 
1576 #ifndef NO_REGEX
1577 /*-
1578  *-----------------------------------------------------------------------
1579  * VarREError --
1580  *	Print the error caused by a regcomp or regexec call.
1581  *
1582  * Results:
1583  *	None.
1584  *
1585  * Side Effects:
1586  *	An error gets printed.
1587  *
1588  *-----------------------------------------------------------------------
1589  */
1590 static void
1591 VarREError(int errnum, regex_t *pat, const char *str)
1592 {
1593     char *errbuf;
1594     int errlen;
1595 
1596     errlen = regerror(errnum, pat, 0, 0);
1597     errbuf = bmake_malloc(errlen);
1598     regerror(errnum, pat, errbuf, errlen);
1599     Error("%s: %s", str, errbuf);
1600     free(errbuf);
1601 }
1602 
1603 
1604 /*-
1605  *-----------------------------------------------------------------------
1606  * VarRESubstitute --
1607  *	Perform a regex substitution on the given word, placing the
1608  *	result in the passed buffer.
1609  *
1610  * Results:
1611  *	TRUE if a space is needed before more characters are added.
1612  *
1613  * Side Effects:
1614  *	None.
1615  *
1616  *-----------------------------------------------------------------------
1617  */
1618 static Boolean
1619 VarRESubstitute(GNode *ctx __unused, Var_Parse_State *vpstate __unused,
1620 		char *word, Boolean addSpace, Buffer *buf,
1621 		void *patternp)
1622 {
1623     VarREPattern *pat;
1624     int xrv;
1625     char *wp;
1626     char *rp;
1627     int added;
1628     int flags = 0;
1629 
1630 #define MAYBE_ADD_SPACE()		\
1631 	if (addSpace && !added)		\
1632 	    Buf_AddByte(buf, ' ');	\
1633 	added = 1
1634 
1635     added = 0;
1636     wp = word;
1637     pat = patternp;
1638 
1639     if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1640 	(VAR_SUB_ONE|VAR_SUB_MATCHED))
1641 	xrv = REG_NOMATCH;
1642     else {
1643     tryagain:
1644 	xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1645     }
1646 
1647     switch (xrv) {
1648     case 0:
1649 	pat->flags |= VAR_SUB_MATCHED;
1650 	if (pat->matches[0].rm_so > 0) {
1651 	    MAYBE_ADD_SPACE();
1652 	    Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1653 	}
1654 
1655 	for (rp = pat->replace; *rp; rp++) {
1656 	    if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1657 		MAYBE_ADD_SPACE();
1658 		Buf_AddByte(buf,rp[1]);
1659 		rp++;
1660 	    }
1661 	    else if ((*rp == '&') ||
1662 		((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1663 		int n;
1664 		const char *subbuf;
1665 		int sublen;
1666 		char errstr[3];
1667 
1668 		if (*rp == '&') {
1669 		    n = 0;
1670 		    errstr[0] = '&';
1671 		    errstr[1] = '\0';
1672 		} else {
1673 		    n = rp[1] - '0';
1674 		    errstr[0] = '\\';
1675 		    errstr[1] = rp[1];
1676 		    errstr[2] = '\0';
1677 		    rp++;
1678 		}
1679 
1680 		if (n > pat->nsub) {
1681 		    Error("No subexpression %s", &errstr[0]);
1682 		    subbuf = "";
1683 		    sublen = 0;
1684 		} else if ((pat->matches[n].rm_so == -1) &&
1685 			   (pat->matches[n].rm_eo == -1)) {
1686 		    Error("No match for subexpression %s", &errstr[0]);
1687 		    subbuf = "";
1688 		    sublen = 0;
1689 	        } else {
1690 		    subbuf = wp + pat->matches[n].rm_so;
1691 		    sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1692 		}
1693 
1694 		if (sublen > 0) {
1695 		    MAYBE_ADD_SPACE();
1696 		    Buf_AddBytes(buf, sublen, subbuf);
1697 		}
1698 	    } else {
1699 		MAYBE_ADD_SPACE();
1700 		Buf_AddByte(buf, *rp);
1701 	    }
1702 	}
1703 	wp += pat->matches[0].rm_eo;
1704 	if (pat->flags & VAR_SUB_GLOBAL) {
1705 	    flags |= REG_NOTBOL;
1706 	    if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
1707 		MAYBE_ADD_SPACE();
1708 		Buf_AddByte(buf, *wp);
1709 		wp++;
1710 
1711 	    }
1712 	    if (*wp)
1713 		goto tryagain;
1714 	}
1715 	if (*wp) {
1716 	    MAYBE_ADD_SPACE();
1717 	    Buf_AddBytes(buf, strlen(wp), wp);
1718 	}
1719 	break;
1720     default:
1721 	VarREError(xrv, &pat->re, "Unexpected regex error");
1722        /* fall through */
1723     case REG_NOMATCH:
1724 	if (*wp) {
1725 	    MAYBE_ADD_SPACE();
1726 	    Buf_AddBytes(buf,strlen(wp),wp);
1727 	}
1728 	break;
1729     }
1730     return(addSpace||added);
1731 }
1732 #endif
1733 
1734 
1735 
1736 /*-
1737  *-----------------------------------------------------------------------
1738  * VarLoopExpand --
1739  *	Implements the :@<temp>@<string>@ modifier of ODE make.
1740  *	We set the temp variable named in pattern.lhs to word and expand
1741  *	pattern.rhs storing the result in the passed buffer.
1742  *
1743  * Input:
1744  *	word		Word to modify
1745  *	addSpace	True if space should be added before
1746  *			other characters
1747  *	buf		Buffer for result
1748  *	pattern		Datafor substitution
1749  *
1750  * Results:
1751  *	TRUE if a space is needed before more characters are added.
1752  *
1753  * Side Effects:
1754  *	None.
1755  *
1756  *-----------------------------------------------------------------------
1757  */
1758 static Boolean
1759 VarLoopExpand(GNode *ctx __unused, Var_Parse_State *vpstate __unused,
1760 	      char *word, Boolean addSpace, Buffer *buf,
1761 	      void *loopp)
1762 {
1763     VarLoop_t	*loop = (VarLoop_t *)loopp;
1764     char *s;
1765     int slen;
1766 
1767     if (word && *word) {
1768         Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT);
1769         s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum);
1770         if (s != NULL && *s != '\0') {
1771             if (addSpace && *s != '\n')
1772                 Buf_AddByte(buf, ' ');
1773             Buf_AddBytes(buf, (slen = strlen(s)), s);
1774             addSpace = (slen > 0 && s[slen - 1] != '\n');
1775             free(s);
1776         }
1777     }
1778     return addSpace;
1779 }
1780 
1781 
1782 /*-
1783  *-----------------------------------------------------------------------
1784  * VarSelectWords --
1785  *	Implements the :[start..end] modifier.
1786  *	This is a special case of VarModify since we want to be able
1787  *	to scan the list backwards if start > end.
1788  *
1789  * Input:
1790  *	str		String whose words should be trimmed
1791  *	seldata		words to select
1792  *
1793  * Results:
1794  *	A string of all the words selected.
1795  *
1796  * Side Effects:
1797  *	None.
1798  *
1799  *-----------------------------------------------------------------------
1800  */
1801 static char *
1802 VarSelectWords(GNode *ctx __unused, Var_Parse_State *vpstate,
1803 	       const char *str, VarSelectWords_t *seldata)
1804 {
1805     Buffer  	  buf;		    /* Buffer for the new string */
1806     Boolean 	  addSpace; 	    /* TRUE if need to add a space to the
1807 				     * buffer before adding the trimmed
1808 				     * word */
1809     char **av;			    /* word list */
1810     char *as;			    /* word list memory */
1811     int ac, i;
1812     int start, end, step;
1813 
1814     Buf_Init(&buf, 0);
1815     addSpace = FALSE;
1816 
1817     if (vpstate->oneBigWord) {
1818 	/* fake what brk_string() would do if there were only one word */
1819 	ac = 1;
1820     	av = bmake_malloc((ac + 1) * sizeof(char *));
1821 	as = bmake_strdup(str);
1822 	av[0] = as;
1823 	av[1] = NULL;
1824     } else {
1825 	av = brk_string(str, &ac, FALSE, &as);
1826     }
1827 
1828     /*
1829      * Now sanitize seldata.
1830      * If seldata->start or seldata->end are negative, convert them to
1831      * the positive equivalents (-1 gets converted to argc, -2 gets
1832      * converted to (argc-1), etc.).
1833      */
1834     if (seldata->start < 0)
1835 	seldata->start = ac + seldata->start + 1;
1836     if (seldata->end < 0)
1837 	seldata->end = ac + seldata->end + 1;
1838 
1839     /*
1840      * We avoid scanning more of the list than we need to.
1841      */
1842     if (seldata->start > seldata->end) {
1843 	start = MIN(ac, seldata->start) - 1;
1844 	end = MAX(0, seldata->end - 1);
1845 	step = -1;
1846     } else {
1847 	start = MAX(0, seldata->start - 1);
1848 	end = MIN(ac, seldata->end);
1849 	step = 1;
1850     }
1851 
1852     for (i = start;
1853 	 (step < 0 && i >= end) || (step > 0 && i < end);
1854 	 i += step) {
1855 	if (av[i] && *av[i]) {
1856 	    if (addSpace && vpstate->varSpace) {
1857 		Buf_AddByte(&buf, vpstate->varSpace);
1858 	    }
1859 	    Buf_AddBytes(&buf, strlen(av[i]), av[i]);
1860 	    addSpace = TRUE;
1861 	}
1862     }
1863 
1864     free(as);
1865     free(av);
1866 
1867     return Buf_Destroy(&buf, FALSE);
1868 }
1869 
1870 
1871 /*-
1872  * VarRealpath --
1873  *	Replace each word with the result of realpath()
1874  *	if successful.
1875  */
1876 static Boolean
1877 VarRealpath(GNode *ctx __unused, Var_Parse_State *vpstate,
1878 	    char *word, Boolean addSpace, Buffer *buf,
1879 	    void *patternp __unused)
1880 {
1881 	struct stat st;
1882 	char rbuf[MAXPATHLEN];
1883 	char *rp;
1884 
1885 	if (addSpace && vpstate->varSpace) {
1886 	    Buf_AddByte(buf, vpstate->varSpace);
1887 	}
1888 	addSpace = TRUE;
1889 	rp = realpath(word, rbuf);
1890 	if (rp && *rp == '/' && stat(rp, &st) == 0)
1891 		word = rp;
1892 
1893 	Buf_AddBytes(buf, strlen(word), word);
1894 	return(addSpace);
1895 }
1896 
1897 /*-
1898  *-----------------------------------------------------------------------
1899  * VarModify --
1900  *	Modify each of the words of the passed string using the given
1901  *	function. Used to implement all modifiers.
1902  *
1903  * Input:
1904  *	str		String whose words should be trimmed
1905  *	modProc		Function to use to modify them
1906  *	datum		Datum to pass it
1907  *
1908  * Results:
1909  *	A string of all the words modified appropriately.
1910  *
1911  * Side Effects:
1912  *	None.
1913  *
1914  *-----------------------------------------------------------------------
1915  */
1916 static char *
1917 VarModify(GNode *ctx, Var_Parse_State *vpstate,
1918     const char *str,
1919     Boolean (*modProc)(GNode *, Var_Parse_State *, char *,
1920 		       Boolean, Buffer *, void *),
1921     void *datum)
1922 {
1923     Buffer  	  buf;		    /* Buffer for the new string */
1924     Boolean 	  addSpace; 	    /* TRUE if need to add a space to the
1925 				     * buffer before adding the trimmed
1926 				     * word */
1927     char **av;			    /* word list */
1928     char *as;			    /* word list memory */
1929     int ac, i;
1930 
1931     Buf_Init(&buf, 0);
1932     addSpace = FALSE;
1933 
1934     if (vpstate->oneBigWord) {
1935 	/* fake what brk_string() would do if there were only one word */
1936 	ac = 1;
1937     	av = bmake_malloc((ac + 1) * sizeof(char *));
1938 	as = bmake_strdup(str);
1939 	av[0] = as;
1940 	av[1] = NULL;
1941     } else {
1942 	av = brk_string(str, &ac, FALSE, &as);
1943     }
1944 
1945     for (i = 0; i < ac; i++) {
1946 	addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum);
1947     }
1948 
1949     free(as);
1950     free(av);
1951 
1952     return Buf_Destroy(&buf, FALSE);
1953 }
1954 
1955 
1956 static int
1957 VarWordCompare(const void *a, const void *b)
1958 {
1959 	int r = strcmp(*(const char * const *)a, *(const char * const *)b);
1960 	return r;
1961 }
1962 
1963 /*-
1964  *-----------------------------------------------------------------------
1965  * VarOrder --
1966  *	Order the words in the string.
1967  *
1968  * Input:
1969  *	str		String whose words should be sorted.
1970  *	otype		How to order: s - sort, x - random.
1971  *
1972  * Results:
1973  *	A string containing the words ordered.
1974  *
1975  * Side Effects:
1976  *	None.
1977  *
1978  *-----------------------------------------------------------------------
1979  */
1980 static char *
1981 VarOrder(const char *str, const char otype)
1982 {
1983     Buffer  	  buf;		    /* Buffer for the new string */
1984     char **av;			    /* word list [first word does not count] */
1985     char *as;			    /* word list memory */
1986     int ac, i;
1987 
1988     Buf_Init(&buf, 0);
1989 
1990     av = brk_string(str, &ac, FALSE, &as);
1991 
1992     if (ac > 0)
1993 	switch (otype) {
1994 	case 's':	/* sort alphabetically */
1995 	    qsort(av, ac, sizeof(char *), VarWordCompare);
1996 	    break;
1997 	case 'x':	/* randomize */
1998 	{
1999 	    int rndidx;
2000 	    char *t;
2001 
2002 	    /*
2003 	     * We will use [ac..2] range for mod factors. This will produce
2004 	     * random numbers in [(ac-1)..0] interval, and minimal
2005 	     * reasonable value for mod factor is 2 (the mod 1 will produce
2006 	     * 0 with probability 1).
2007 	     */
2008 	    for (i = ac-1; i > 0; i--) {
2009 		rndidx = random() % (i + 1);
2010 		if (i != rndidx) {
2011 		    t = av[i];
2012 		    av[i] = av[rndidx];
2013 		    av[rndidx] = t;
2014 		}
2015 	    }
2016 	}
2017 	} /* end of switch */
2018 
2019     for (i = 0; i < ac; i++) {
2020 	Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2021 	if (i != ac - 1)
2022 	    Buf_AddByte(&buf, ' ');
2023     }
2024 
2025     free(as);
2026     free(av);
2027 
2028     return Buf_Destroy(&buf, FALSE);
2029 }
2030 
2031 
2032 /*-
2033  *-----------------------------------------------------------------------
2034  * VarUniq --
2035  *	Remove adjacent duplicate words.
2036  *
2037  * Input:
2038  *	str		String whose words should be sorted
2039  *
2040  * Results:
2041  *	A string containing the resulting words.
2042  *
2043  * Side Effects:
2044  *	None.
2045  *
2046  *-----------------------------------------------------------------------
2047  */
2048 static char *
2049 VarUniq(const char *str)
2050 {
2051     Buffer	  buf;		    /* Buffer for new string */
2052     char 	**av;		    /* List of words to affect */
2053     char 	 *as;		    /* Word list memory */
2054     int 	  ac, i, j;
2055 
2056     Buf_Init(&buf, 0);
2057     av = brk_string(str, &ac, FALSE, &as);
2058 
2059     if (ac > 1) {
2060 	for (j = 0, i = 1; i < ac; i++)
2061 	    if (strcmp(av[i], av[j]) != 0 && (++j != i))
2062 		av[j] = av[i];
2063 	ac = j + 1;
2064     }
2065 
2066     for (i = 0; i < ac; i++) {
2067 	Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2068 	if (i != ac - 1)
2069 	    Buf_AddByte(&buf, ' ');
2070     }
2071 
2072     free(as);
2073     free(av);
2074 
2075     return Buf_Destroy(&buf, FALSE);
2076 }
2077 
2078 
2079 /*-
2080  *-----------------------------------------------------------------------
2081  * VarGetPattern --
2082  *	Pass through the tstr looking for 1) escaped delimiters,
2083  *	'$'s and backslashes (place the escaped character in
2084  *	uninterpreted) and 2) unescaped $'s that aren't before
2085  *	the delimiter (expand the variable substitution unless flags
2086  *	has VAR_NOSUBST set).
2087  *	Return the expanded string or NULL if the delimiter was missing
2088  *	If pattern is specified, handle escaped ampersands, and replace
2089  *	unescaped ampersands with the lhs of the pattern.
2090  *
2091  * Results:
2092  *	A string of all the words modified appropriately.
2093  *	If length is specified, return the string length of the buffer
2094  *	If flags is specified and the last character of the pattern is a
2095  *	$ set the VAR_MATCH_END bit of flags.
2096  *
2097  * Side Effects:
2098  *	None.
2099  *-----------------------------------------------------------------------
2100  */
2101 static char *
2102 VarGetPattern(GNode *ctxt, Var_Parse_State *vpstate __unused,
2103 	      int errnum, const char **tstr, int delim, int *flags,
2104 	      int *length, VarPattern *pattern)
2105 {
2106     const char *cp;
2107     char *rstr;
2108     Buffer buf;
2109     int junk;
2110 
2111     Buf_Init(&buf, 0);
2112     if (length == NULL)
2113 	length = &junk;
2114 
2115 #define IS_A_MATCH(cp, delim) \
2116     ((cp[0] == '\\') && ((cp[1] == delim) ||  \
2117      (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
2118 
2119     /*
2120      * Skim through until the matching delimiter is found;
2121      * pick up variable substitutions on the way. Also allow
2122      * backslashes to quote the delimiter, $, and \, but don't
2123      * touch other backslashes.
2124      */
2125     for (cp = *tstr; *cp && (*cp != delim); cp++) {
2126 	if (IS_A_MATCH(cp, delim)) {
2127 	    Buf_AddByte(&buf, cp[1]);
2128 	    cp++;
2129 	} else if (*cp == '$') {
2130 	    if (cp[1] == delim) {
2131 		if (flags == NULL)
2132 		    Buf_AddByte(&buf, *cp);
2133 		else
2134 		    /*
2135 		     * Unescaped $ at end of pattern => anchor
2136 		     * pattern at end.
2137 		     */
2138 		    *flags |= VAR_MATCH_END;
2139 	    } else {
2140 		if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
2141 		    char   *cp2;
2142 		    int     len;
2143 		    void   *freeIt;
2144 
2145 		    /*
2146 		     * If unescaped dollar sign not before the
2147 		     * delimiter, assume it's a variable
2148 		     * substitution and recurse.
2149 		     */
2150 		    cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2151 		    Buf_AddBytes(&buf, strlen(cp2), cp2);
2152 		    if (freeIt)
2153 			free(freeIt);
2154 		    cp += len - 1;
2155 		} else {
2156 		    const char *cp2 = &cp[1];
2157 
2158 		    if (*cp2 == PROPEN || *cp2 == BROPEN) {
2159 			/*
2160 			 * Find the end of this variable reference
2161 			 * and suck it in without further ado.
2162 			 * It will be interperated later.
2163 			 */
2164 			int have = *cp2;
2165 			int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
2166 			int depth = 1;
2167 
2168 			for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
2169 			    if (cp2[-1] != '\\') {
2170 				if (*cp2 == have)
2171 				    ++depth;
2172 				if (*cp2 == want)
2173 				    --depth;
2174 			    }
2175 			}
2176 			Buf_AddBytes(&buf, cp2 - cp, cp);
2177 			cp = --cp2;
2178 		    } else
2179 			Buf_AddByte(&buf, *cp);
2180 		}
2181 	    }
2182 	}
2183 	else if (pattern && *cp == '&')
2184 	    Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs);
2185 	else
2186 	    Buf_AddByte(&buf, *cp);
2187     }
2188 
2189     if (*cp != delim) {
2190 	*tstr = cp;
2191 	*length = 0;
2192 	return NULL;
2193     }
2194 
2195     *tstr = ++cp;
2196     *length = Buf_Size(&buf);
2197     rstr = Buf_Destroy(&buf, FALSE);
2198     if (DEBUG(VAR))
2199 	fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr);
2200     return rstr;
2201 }
2202 
2203 /*-
2204  *-----------------------------------------------------------------------
2205  * VarQuote --
2206  *	Quote shell meta-characters in the string
2207  *
2208  * Results:
2209  *	The quoted string
2210  *
2211  * Side Effects:
2212  *	None.
2213  *
2214  *-----------------------------------------------------------------------
2215  */
2216 static char *
2217 VarQuote(char *str)
2218 {
2219 
2220     Buffer  	  buf;
2221     /* This should cover most shells :-( */
2222     static const char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
2223     const char	*newline;
2224     size_t len, nlen;
2225 
2226     if ((newline = Shell_GetNewline()) == NULL)
2227 	    newline = "\\\n";
2228     nlen = strlen(newline);
2229 
2230     Buf_Init(&buf, 0);
2231     while (*str != '\0') {
2232 	if ((len = strcspn(str, meta)) != 0) {
2233 	    Buf_AddBytes(&buf, len, str);
2234 	    str += len;
2235 	} else if (*str == '\n') {
2236 	    Buf_AddBytes(&buf, nlen, newline);
2237 	    ++str;
2238 	} else {
2239 	    Buf_AddByte(&buf, '\\');
2240 	    Buf_AddByte(&buf, *str);
2241 	    ++str;
2242 	}
2243     }
2244     str = Buf_Destroy(&buf, FALSE);
2245     if (DEBUG(VAR))
2246 	fprintf(debug_file, "QuoteMeta: [%s]\n", str);
2247     return str;
2248 }
2249 
2250 /*-
2251  *-----------------------------------------------------------------------
2252  * VarChangeCase --
2253  *      Change the string to all uppercase or all lowercase
2254  *
2255  * Input:
2256  *	str		String to modify
2257  *	upper		TRUE -> uppercase, else lowercase
2258  *
2259  * Results:
2260  *      The string with case changed
2261  *
2262  * Side Effects:
2263  *      None.
2264  *
2265  *-----------------------------------------------------------------------
2266  */
2267 static char *
2268 VarChangeCase(char *str, int upper)
2269 {
2270    Buffer         buf;
2271    int            (*modProc)(int);
2272 
2273    modProc = (upper ? toupper : tolower);
2274    Buf_Init(&buf, 0);
2275    for (; *str ; str++) {
2276        Buf_AddByte(&buf, modProc(*str));
2277    }
2278    return Buf_Destroy(&buf, FALSE);
2279 }
2280 
2281 /*
2282  * Now we need to apply any modifiers the user wants applied.
2283  * These are:
2284  *  	  :M<pattern>	words which match the given <pattern>.
2285  *  			<pattern> is of the standard file
2286  *  			wildcarding form.
2287  *  	  :N<pattern>	words which do not match the given <pattern>.
2288  *  	  :S<d><pat1><d><pat2><d>[1gW]
2289  *  			Substitute <pat2> for <pat1> in the value
2290  *  	  :C<d><pat1><d><pat2><d>[1gW]
2291  *  			Substitute <pat2> for regex <pat1> in the value
2292  *  	  :H		Substitute the head of each word
2293  *  	  :T		Substitute the tail of each word
2294  *  	  :E		Substitute the extension (minus '.') of
2295  *  			each word
2296  *  	  :R		Substitute the root of each word
2297  *  			(pathname minus the suffix).
2298  *	  :O		("Order") Alphabeticaly sort words in variable.
2299  *	  :Ox		("intermiX") Randomize words in variable.
2300  *	  :u		("uniq") Remove adjacent duplicate words.
2301  *	  :tu		Converts the variable contents to uppercase.
2302  *	  :tl		Converts the variable contents to lowercase.
2303  *	  :ts[c]	Sets varSpace - the char used to
2304  *			separate words to 'c'. If 'c' is
2305  *			omitted then no separation is used.
2306  *	  :tW		Treat the variable contents as a single
2307  *			word, even if it contains spaces.
2308  *			(Mnemonic: one big 'W'ord.)
2309  *	  :tw		Treat the variable contents as multiple
2310  *			space-separated words.
2311  *			(Mnemonic: many small 'w'ords.)
2312  *	  :[index]	Select a single word from the value.
2313  *	  :[start..end]	Select multiple words from the value.
2314  *	  :[*] or :[0]	Select the entire value, as a single
2315  *			word.  Equivalent to :tW.
2316  *	  :[@]		Select the entire value, as multiple
2317  *			words.	Undoes the effect of :[*].
2318  *			Equivalent to :tw.
2319  *	  :[#]		Returns the number of words in the value.
2320  *
2321  *	  :?<true-value>:<false-value>
2322  *			If the variable evaluates to true, return
2323  *			true value, else return the second value.
2324  *    	  :lhs=rhs  	Like :S, but the rhs goes to the end of
2325  *    			the invocation.
2326  *	  :sh		Treat the current value as a command
2327  *			to be run, new value is its output.
2328  * The following added so we can handle ODE makefiles.
2329  *	  :@<tmpvar>@<newval>@
2330  *			Assign a temporary local variable <tmpvar>
2331  *			to the current value of each word in turn
2332  *			and replace each word with the result of
2333  *			evaluating <newval>
2334  *	  :D<newval>	Use <newval> as value if variable defined
2335  *	  :U<newval>	Use <newval> as value if variable undefined
2336  *	  :L		Use the name of the variable as the value.
2337  *	  :P		Use the path of the node that has the same
2338  *			name as the variable as the value.  This
2339  *			basically includes an implied :L so that
2340  *			the common method of refering to the path
2341  *			of your dependent 'x' in a rule is to use
2342  *			the form '${x:P}'.
2343  *	  :!<cmd>!	Run cmd much the same as :sh run's the
2344  *			current value of the variable.
2345  * The ::= modifiers, actually assign a value to the variable.
2346  * Their main purpose is in supporting modifiers of .for loop
2347  * iterators and other obscure uses.  They always expand to
2348  * nothing.  In a target rule that would otherwise expand to an
2349  * empty line they can be preceded with @: to keep make happy.
2350  * Eg.
2351  *
2352  * foo:	.USE
2353  * .for i in ${.TARGET} ${.TARGET:R}.gz
2354  * 	@: ${t::=$i}
2355  *	@echo blah ${t:T}
2356  * .endfor
2357  *
2358  *	  ::=<str>	Assigns <str> as the new value of variable.
2359  *	  ::?=<str>	Assigns <str> as value of variable if
2360  *			it was not already set.
2361  *	  ::+=<str>	Appends <str> to variable.
2362  *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
2363  *			variable.
2364  */
2365 
2366 static char *
2367 ApplyModifiers(char *nstr, const char *tstr,
2368 	       int startc, int endc,
2369 	       Var *v, GNode *ctxt, Boolean errnum,
2370 	       int *lengthPtr, void **freePtr)
2371 {
2372     const char 	   *start;
2373     const char     *cp;    	/* Secondary pointer into str (place marker
2374 				 * for tstr) */
2375     char	   *newStr;	/* New value to return */
2376     char	    termc;	/* Character which terminated scan */
2377     int             cnt;	/* Used to count brace pairs when variable in
2378 				 * in parens or braces */
2379     char	delim;
2380     int		modifier;	/* that we are processing */
2381     Var_Parse_State parsestate; /* Flags passed to helper functions */
2382 
2383     delim = '\0';
2384     parsestate.oneBigWord = FALSE;
2385     parsestate.varSpace = ' ';	/* word separator */
2386 
2387     start = cp = tstr;
2388 
2389     while (*tstr && *tstr != endc) {
2390 
2391 	if (*tstr == '$') {
2392 	    /*
2393 	     * We have some complex modifiers in a variable.
2394 	     */
2395 	    void *freeIt;
2396 	    char *rval;
2397 	    int rlen;
2398 
2399 	    rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
2400 
2401 	    if (DEBUG(VAR)) {
2402 		fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
2403 		       rval, rlen, tstr, rlen, tstr + rlen);
2404 	    }
2405 
2406 	    tstr += rlen;
2407 
2408 	    if (rval != NULL && *rval) {
2409 		int used;
2410 
2411 		nstr = ApplyModifiers(nstr, rval,
2412 				      0, 0,
2413 				      v, ctxt, errnum, &used, freePtr);
2414 		if (nstr == var_Error
2415 		    || (nstr == varNoError && errnum == 0)
2416 		    || strlen(rval) != (size_t) used) {
2417 		    if (freeIt)
2418 			free(freeIt);
2419 		    goto out;		/* error already reported */
2420 		}
2421 	    }
2422 	    if (freeIt)
2423 		free(freeIt);
2424 	    if (*tstr == ':')
2425 		tstr++;
2426 	    else if (!*tstr && endc) {
2427 		Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name);
2428 		goto out;
2429 	    }
2430 	    continue;
2431 	}
2432 	if (DEBUG(VAR)) {
2433 	    fprintf(debug_file, "Applying :%c to \"%s\"\n", *tstr, nstr);
2434 	}
2435 	newStr = var_Error;
2436 	switch ((modifier = *tstr)) {
2437 	case ':':
2438 	    {
2439 		if (tstr[1] == '=' ||
2440 		    (tstr[2] == '=' &&
2441 		     (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
2442 		    /*
2443 		     * "::=", "::!=", "::+=", or "::?="
2444 		     */
2445 		    GNode *v_ctxt;		/* context where v belongs */
2446 		    const char *emsg;
2447 		    char *sv_name;
2448 		    VarPattern	pattern;
2449 		    int	how;
2450 
2451 		    if (v->name[0] == 0)
2452 			goto bad_modifier;
2453 
2454 		    v_ctxt = ctxt;
2455 		    sv_name = NULL;
2456 		    ++tstr;
2457 		    if (v->flags & VAR_JUNK) {
2458 			/*
2459 			 * We need to bmake_strdup() it incase
2460 			 * VarGetPattern() recurses.
2461 			 */
2462 			sv_name = v->name;
2463 			v->name = bmake_strdup(v->name);
2464 		    } else if (ctxt != VAR_GLOBAL) {
2465 			Var *gv = VarFind(v->name, ctxt, 0);
2466 			if (gv == NULL)
2467 			    v_ctxt = VAR_GLOBAL;
2468 			else
2469 			    VarFreeEnv(gv, TRUE);
2470 		    }
2471 
2472 		    switch ((how = *tstr)) {
2473 		    case '+':
2474 		    case '?':
2475 		    case '!':
2476 			cp = &tstr[2];
2477 			break;
2478 		    default:
2479 			cp = ++tstr;
2480 			break;
2481 		    }
2482 		    delim = BRCLOSE;
2483 		    pattern.flags = 0;
2484 
2485 		    pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2486 						&cp, delim, NULL,
2487 						&pattern.rightLen,
2488 						NULL);
2489 		    if (v->flags & VAR_JUNK) {
2490 			/* restore original name */
2491 			free(v->name);
2492 			v->name = sv_name;
2493 		    }
2494 		    if (pattern.rhs == NULL)
2495 			goto cleanup;
2496 
2497 		    termc = *--cp;
2498 		    delim = '\0';
2499 
2500 		    switch (how) {
2501 		    case '+':
2502 			Var_Append(v->name, pattern.rhs, v_ctxt);
2503 			break;
2504 		    case '!':
2505 			newStr = Cmd_Exec(pattern.rhs, &emsg);
2506 			if (emsg)
2507 			    Error(emsg, nstr);
2508 			else
2509 			    Var_Set(v->name, newStr,  v_ctxt, 0);
2510 			if (newStr)
2511 			    free(newStr);
2512 			break;
2513 		    case '?':
2514 			if ((v->flags & VAR_JUNK) == 0)
2515 			    break;
2516 			/* FALLTHROUGH */
2517 		    default:
2518 			Var_Set(v->name, pattern.rhs, v_ctxt, 0);
2519 			break;
2520 		    }
2521 		    free(UNCONST(pattern.rhs));
2522 		    newStr = var_Error;
2523 		    break;
2524 		}
2525 		goto default_case; /* "::<unrecognised>" */
2526 	    }
2527 	case '@':
2528 	    {
2529 		VarLoop_t	loop;
2530 		int flags = VAR_NOSUBST;
2531 
2532 		cp = ++tstr;
2533 		delim = '@';
2534 		if ((loop.tvar = VarGetPattern(ctxt, &parsestate, errnum,
2535 					       &cp, delim,
2536 					       &flags, &loop.tvarLen,
2537 					       NULL)) == NULL)
2538 		    goto cleanup;
2539 
2540 		if ((loop.str = VarGetPattern(ctxt, &parsestate, errnum,
2541 					      &cp, delim,
2542 					      &flags, &loop.strLen,
2543 					      NULL)) == NULL)
2544 		    goto cleanup;
2545 
2546 		termc = *cp;
2547 		delim = '\0';
2548 
2549 		loop.errnum = errnum;
2550 		loop.ctxt = ctxt;
2551 		newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
2552 				   &loop);
2553 		free(loop.tvar);
2554 		free(loop.str);
2555 		break;
2556 	    }
2557 	case 'D':
2558 	case 'U':
2559 	    {
2560 		Buffer  buf;    	/* Buffer for patterns */
2561 		int	    wantit;	/* want data in buffer */
2562 
2563 		/*
2564 		 * Pass through tstr looking for 1) escaped delimiters,
2565 		 * '$'s and backslashes (place the escaped character in
2566 		 * uninterpreted) and 2) unescaped $'s that aren't before
2567 		 * the delimiter (expand the variable substitution).
2568 		 * The result is left in the Buffer buf.
2569 		 */
2570 		Buf_Init(&buf, 0);
2571 		for (cp = tstr + 1;
2572 		     *cp != endc && *cp != ':' && *cp != '\0';
2573 		     cp++) {
2574 		    if ((*cp == '\\') &&
2575 			((cp[1] == ':') ||
2576 			 (cp[1] == '$') ||
2577 			 (cp[1] == endc) ||
2578 			 (cp[1] == '\\')))
2579 			{
2580 			    Buf_AddByte(&buf, cp[1]);
2581 			    cp++;
2582 			} else if (*cp == '$') {
2583 			    /*
2584 			     * If unescaped dollar sign, assume it's a
2585 			     * variable substitution and recurse.
2586 			     */
2587 			    char    *cp2;
2588 			    int	    len;
2589 			    void    *freeIt;
2590 
2591 			    cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2592 			    Buf_AddBytes(&buf, strlen(cp2), cp2);
2593 			    if (freeIt)
2594 				free(freeIt);
2595 			    cp += len - 1;
2596 			} else {
2597 			    Buf_AddByte(&buf, *cp);
2598 			}
2599 		}
2600 
2601 		termc = *cp;
2602 
2603 		if (*tstr == 'U')
2604 		    wantit = ((v->flags & VAR_JUNK) != 0);
2605 		else
2606 		    wantit = ((v->flags & VAR_JUNK) == 0);
2607 		if ((v->flags & VAR_JUNK) != 0)
2608 		    v->flags |= VAR_KEEP;
2609 		if (wantit) {
2610 		    newStr = Buf_Destroy(&buf, FALSE);
2611 		} else {
2612 		    newStr = nstr;
2613 		    Buf_Destroy(&buf, TRUE);
2614 		}
2615 		break;
2616 	    }
2617 	case 'L':
2618 	    {
2619 		if ((v->flags & VAR_JUNK) != 0)
2620 		    v->flags |= VAR_KEEP;
2621 		newStr = bmake_strdup(v->name);
2622 		cp = ++tstr;
2623 		termc = *tstr;
2624 		break;
2625 	    }
2626 	case 'P':
2627 	    {
2628 		GNode *gn;
2629 
2630 		if ((v->flags & VAR_JUNK) != 0)
2631 		    v->flags |= VAR_KEEP;
2632 		gn = Targ_FindNode(v->name, TARG_NOCREATE);
2633 		if (gn == NULL || gn->type & OP_NOPATH) {
2634 		    newStr = NULL;
2635 		} else if (gn->path) {
2636 		    newStr = bmake_strdup(gn->path);
2637 		} else {
2638 		    newStr = Dir_FindFile(v->name, Suff_FindPath(gn));
2639 		}
2640 		if (!newStr) {
2641 		    newStr = bmake_strdup(v->name);
2642 		}
2643 		cp = ++tstr;
2644 		termc = *tstr;
2645 		break;
2646 	    }
2647 	case '!':
2648 	    {
2649 		const char *emsg;
2650 		VarPattern 	    pattern;
2651 		pattern.flags = 0;
2652 
2653 		delim = '!';
2654 
2655 		cp = ++tstr;
2656 		if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2657 						 &cp, delim,
2658 						 NULL, &pattern.rightLen,
2659 						 NULL)) == NULL)
2660 		    goto cleanup;
2661 		newStr = Cmd_Exec(pattern.rhs, &emsg);
2662 		free(UNCONST(pattern.rhs));
2663 		if (emsg)
2664 		    Error(emsg, nstr);
2665 		termc = *cp;
2666 		delim = '\0';
2667 		if (v->flags & VAR_JUNK) {
2668 		    v->flags |= VAR_KEEP;
2669 		}
2670 		break;
2671 	    }
2672 	case '[':
2673 	    {
2674 		/*
2675 		 * Look for the closing ']', recursively
2676 		 * expanding any embedded variables.
2677 		 *
2678 		 * estr is a pointer to the expanded result,
2679 		 * which we must free().
2680 		 */
2681 		char *estr;
2682 
2683 		cp = tstr+1; /* point to char after '[' */
2684 		delim = ']'; /* look for closing ']' */
2685 		estr = VarGetPattern(ctxt, &parsestate,
2686 				     errnum, &cp, delim,
2687 				     NULL, NULL, NULL);
2688 		if (estr == NULL)
2689 		    goto cleanup; /* report missing ']' */
2690 		/* now cp points just after the closing ']' */
2691 		delim = '\0';
2692 		if (cp[0] != ':' && cp[0] != endc) {
2693 		    /* Found junk after ']' */
2694 		    free(estr);
2695 		    goto bad_modifier;
2696 		}
2697 		if (estr[0] == '\0') {
2698 		    /* Found empty square brackets in ":[]". */
2699 		    free(estr);
2700 		    goto bad_modifier;
2701 		} else if (estr[0] == '#' && estr[1] == '\0') {
2702 		    /* Found ":[#]" */
2703 
2704 		    /*
2705 		     * We will need enough space for the decimal
2706 		     * representation of an int.  We calculate the
2707 		     * space needed for the octal representation,
2708 		     * and add enough slop to cope with a '-' sign
2709 		     * (which should never be needed) and a '\0'
2710 		     * string terminator.
2711 		     */
2712 		    int newStrSize =
2713 			(sizeof(int) * CHAR_BIT + 2) / 3 + 2;
2714 
2715 		    newStr = bmake_malloc(newStrSize);
2716 		    if (parsestate.oneBigWord) {
2717 			strncpy(newStr, "1", newStrSize);
2718 		    } else {
2719 			/* XXX: brk_string() is a rather expensive
2720 			 * way of counting words. */
2721 			char **av;
2722 			char *as;
2723 			int ac;
2724 
2725 			av = brk_string(nstr, &ac, FALSE, &as);
2726 			snprintf(newStr, newStrSize,  "%d", ac);
2727 			free(as);
2728 			free(av);
2729 		    }
2730 		    termc = *cp;
2731 		    free(estr);
2732 		    break;
2733 		} else if (estr[0] == '*' && estr[1] == '\0') {
2734 		    /* Found ":[*]" */
2735 		    parsestate.oneBigWord = TRUE;
2736 		    newStr = nstr;
2737 		    termc = *cp;
2738 		    free(estr);
2739 		    break;
2740 		} else if (estr[0] == '@' && estr[1] == '\0') {
2741 		    /* Found ":[@]" */
2742 		    parsestate.oneBigWord = FALSE;
2743 		    newStr = nstr;
2744 		    termc = *cp;
2745 		    free(estr);
2746 		    break;
2747 		} else {
2748 		    /*
2749 		     * We expect estr to contain a single
2750 		     * integer for :[N], or two integers
2751 		     * separated by ".." for :[start..end].
2752 		     */
2753 		    char *ep;
2754 
2755 		    VarSelectWords_t seldata = { 0, 0 };
2756 
2757 		    seldata.start = strtol(estr, &ep, 0);
2758 		    if (ep == estr) {
2759 			/* Found junk instead of a number */
2760 			free(estr);
2761 			goto bad_modifier;
2762 		    } else if (ep[0] == '\0') {
2763 			/* Found only one integer in :[N] */
2764 			seldata.end = seldata.start;
2765 		    } else if (ep[0] == '.' && ep[1] == '.' &&
2766 			       ep[2] != '\0') {
2767 			/* Expecting another integer after ".." */
2768 			ep += 2;
2769 			seldata.end = strtol(ep, &ep, 0);
2770 			if (ep[0] != '\0') {
2771 			    /* Found junk after ".." */
2772 			    free(estr);
2773 			    goto bad_modifier;
2774 			}
2775 		    } else {
2776 			/* Found junk instead of ".." */
2777 			free(estr);
2778 			goto bad_modifier;
2779 		    }
2780 		    /*
2781 		     * Now seldata is properly filled in,
2782 		     * but we still have to check for 0 as
2783 		     * a special case.
2784 		     */
2785 		    if (seldata.start == 0 && seldata.end == 0) {
2786 			/* ":[0]" or perhaps ":[0..0]" */
2787 			parsestate.oneBigWord = TRUE;
2788 			newStr = nstr;
2789 			termc = *cp;
2790 			free(estr);
2791 			break;
2792 		    } else if (seldata.start == 0 ||
2793 			       seldata.end == 0) {
2794 			/* ":[0..N]" or ":[N..0]" */
2795 			free(estr);
2796 			goto bad_modifier;
2797 		    }
2798 		    /*
2799 		     * Normal case: select the words
2800 		     * described by seldata.
2801 		     */
2802 		    newStr = VarSelectWords(ctxt, &parsestate,
2803 					    nstr, &seldata);
2804 
2805 		    termc = *cp;
2806 		    free(estr);
2807 		    break;
2808 		}
2809 
2810 	    }
2811 	case 't':
2812 	    {
2813 		cp = tstr + 1;	/* make sure it is set */
2814 		if (tstr[1] != endc && tstr[1] != ':') {
2815 		    if (tstr[1] == 's') {
2816 			/*
2817 			 * Use the char (if any) at tstr[2]
2818 			 * as the word separator.
2819 			 */
2820 			VarPattern pattern;
2821 
2822 			if (tstr[2] != endc &&
2823 			    (tstr[3] == endc || tstr[3] == ':')) {
2824 			    /* ":ts<unrecognised><endc>" or
2825 			     * ":ts<unrecognised>:" */
2826 			    parsestate.varSpace = tstr[2];
2827 			    cp = tstr + 3;
2828 			} else if (tstr[2] == endc || tstr[2] == ':') {
2829 			    /* ":ts<endc>" or ":ts:" */
2830 			    parsestate.varSpace = 0; /* no separator */
2831 			    cp = tstr + 2;
2832 			} else if (tstr[2] == '\\') {
2833 			    switch (tstr[3]) {
2834 			    case 'n':
2835 				parsestate.varSpace = '\n';
2836 				cp = tstr + 4;
2837 				break;
2838 			    case 't':
2839 				parsestate.varSpace = '\t';
2840 				cp = tstr + 4;
2841 				break;
2842 			    default:
2843 				if (isdigit((unsigned char)tstr[3])) {
2844 				    char *ep;
2845 
2846 				    parsestate.varSpace =
2847 					strtoul(&tstr[3], &ep, 0);
2848 				    if (*ep != ':' && *ep != endc)
2849 					goto bad_modifier;
2850 				    cp = ep;
2851 				} else {
2852 				    /*
2853 				     * ":ts<backslash><unrecognised>".
2854 				     */
2855 				    goto bad_modifier;
2856 				}
2857 				break;
2858 			    }
2859 			} else {
2860 			    /*
2861 			     * Found ":ts<unrecognised><unrecognised>".
2862 			     */
2863 			    goto bad_modifier;
2864 			}
2865 
2866 			termc = *cp;
2867 
2868 			/*
2869 			 * We cannot be certain that VarModify
2870 			 * will be used - even if there is a
2871 			 * subsequent modifier, so do a no-op
2872 			 * VarSubstitute now to for str to be
2873 			 * re-expanded without the spaces.
2874 			 */
2875 			pattern.flags = VAR_SUB_ONE;
2876 			pattern.lhs = pattern.rhs = "\032";
2877 			pattern.leftLen = pattern.rightLen = 1;
2878 
2879 			newStr = VarModify(ctxt, &parsestate, nstr,
2880 					   VarSubstitute,
2881 					   &pattern);
2882 		    } else if (tstr[2] == endc || tstr[2] == ':') {
2883 			/*
2884 			 * Check for two-character options:
2885 			 * ":tu", ":tl"
2886 			 */
2887 			if (tstr[1] == 'A') { /* absolute path */
2888 			    newStr = VarModify(ctxt, &parsestate, nstr,
2889 					       VarRealpath, NULL);
2890 			    cp = tstr + 2;
2891 			    termc = *cp;
2892 			} else if (tstr[1] == 'u' || tstr[1] == 'l') {
2893 			    newStr = VarChangeCase(nstr, (tstr[1] == 'u'));
2894 			    cp = tstr + 2;
2895 			    termc = *cp;
2896 			} else if (tstr[1] == 'W' || tstr[1] == 'w') {
2897 			    parsestate.oneBigWord = (tstr[1] == 'W');
2898 			    newStr = nstr;
2899 			    cp = tstr + 2;
2900 			    termc = *cp;
2901 			} else {
2902 			    /* Found ":t<unrecognised>:" or
2903 			     * ":t<unrecognised><endc>". */
2904 			    goto bad_modifier;
2905 			}
2906 		    } else {
2907 			/*
2908 			 * Found ":t<unrecognised><unrecognised>".
2909 			 */
2910 			goto bad_modifier;
2911 		    }
2912 		} else {
2913 		    /*
2914 		     * Found ":t<endc>" or ":t:".
2915 		     */
2916 		    goto bad_modifier;
2917 		}
2918 		break;
2919 	    }
2920 	case 'N':
2921 	case 'M':
2922 	    {
2923 		char    *pattern;
2924 		const char *endpat; /* points just after end of pattern */
2925 		char    *cp2;
2926 		Boolean copy;	/* pattern should be, or has been, copied */
2927 		Boolean needSubst;
2928 		int nest;
2929 
2930 		copy = FALSE;
2931 		needSubst = FALSE;
2932 		nest = 1;
2933 		/*
2934 		 * In the loop below, ignore ':' unless we are at
2935 		 * (or back to) the original brace level.
2936 		 * XXX This will likely not work right if $() and ${}
2937 		 * are intermixed.
2938 		 */
2939 		for (cp = tstr + 1;
2940 		     *cp != '\0' && !(*cp == ':' && nest == 1);
2941 		     cp++)
2942 		    {
2943 			if (*cp == '\\' &&
2944 			    (cp[1] == ':' ||
2945 			     cp[1] == endc || cp[1] == startc)) {
2946 			    if (!needSubst) {
2947 				copy = TRUE;
2948 			    }
2949 			    cp++;
2950 			    continue;
2951 			}
2952 			if (*cp == '$') {
2953 			    needSubst = TRUE;
2954 			}
2955 			if (*cp == '(' || *cp == '{')
2956 			    ++nest;
2957 			if (*cp == ')' || *cp == '}') {
2958 			    --nest;
2959 			    if (nest == 0)
2960 				break;
2961 			}
2962 		    }
2963 		termc = *cp;
2964 		endpat = cp;
2965 		if (copy) {
2966 		    /*
2967 		     * Need to compress the \:'s out of the pattern, so
2968 		     * allocate enough room to hold the uncompressed
2969 		     * pattern (note that cp started at tstr+1, so
2970 		     * cp - tstr takes the null byte into account) and
2971 		     * compress the pattern into the space.
2972 		     */
2973 		    pattern = bmake_malloc(cp - tstr);
2974 		    for (cp2 = pattern, cp = tstr + 1;
2975 			 cp < endpat;
2976 			 cp++, cp2++)
2977 			{
2978 			    if ((*cp == '\\') && (cp+1 < endpat) &&
2979 				(cp[1] == ':' || cp[1] == endc)) {
2980 				cp++;
2981 			    }
2982 			    *cp2 = *cp;
2983 			}
2984 		    *cp2 = '\0';
2985 		    endpat = cp2;
2986 		} else {
2987 		    /*
2988 		     * Either Var_Subst or VarModify will need a
2989 		     * nul-terminated string soon, so construct one now.
2990 		     */
2991 		    pattern = bmake_strndup(tstr+1, endpat - (tstr + 1));
2992 		}
2993 		if (needSubst) {
2994 		    /*
2995 		     * pattern contains embedded '$', so use Var_Subst to
2996 		     * expand it.
2997 		     */
2998 		    cp2 = pattern;
2999 		    pattern = Var_Subst(NULL, cp2, ctxt, errnum);
3000 		    free(cp2);
3001 		}
3002 		if (DEBUG(VAR))
3003 		    fprintf(debug_file, "Pattern for [%s] is [%s]\n", nstr,
3004 			pattern);
3005 		if (*tstr == 'M') {
3006 		    newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
3007 				       pattern);
3008 		} else {
3009 		    newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
3010 				       pattern);
3011 		}
3012 		free(pattern);
3013 		break;
3014 	    }
3015 	case 'S':
3016 	    {
3017 		VarPattern 	    pattern;
3018 		Var_Parse_State tmpparsestate;
3019 
3020 		pattern.flags = 0;
3021 		tmpparsestate = parsestate;
3022 		delim = tstr[1];
3023 		tstr += 2;
3024 
3025 		/*
3026 		 * If pattern begins with '^', it is anchored to the
3027 		 * start of the word -- skip over it and flag pattern.
3028 		 */
3029 		if (*tstr == '^') {
3030 		    pattern.flags |= VAR_MATCH_START;
3031 		    tstr += 1;
3032 		}
3033 
3034 		cp = tstr;
3035 		if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3036 						 &cp, delim,
3037 						 &pattern.flags,
3038 						 &pattern.leftLen,
3039 						 NULL)) == NULL)
3040 		    goto cleanup;
3041 
3042 		if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3043 						 &cp, delim, NULL,
3044 						 &pattern.rightLen,
3045 						 &pattern)) == NULL)
3046 		    goto cleanup;
3047 
3048 		/*
3049 		 * Check for global substitution. If 'g' after the final
3050 		 * delimiter, substitution is global and is marked that
3051 		 * way.
3052 		 */
3053 		for (;; cp++) {
3054 		    switch (*cp) {
3055 		    case 'g':
3056 			pattern.flags |= VAR_SUB_GLOBAL;
3057 			continue;
3058 		    case '1':
3059 			pattern.flags |= VAR_SUB_ONE;
3060 			continue;
3061 		    case 'W':
3062 			tmpparsestate.oneBigWord = TRUE;
3063 			continue;
3064 		    }
3065 		    break;
3066 		}
3067 
3068 		termc = *cp;
3069 		newStr = VarModify(ctxt, &tmpparsestate, nstr,
3070 				   VarSubstitute,
3071 				   &pattern);
3072 
3073 		/*
3074 		 * Free the two strings.
3075 		 */
3076 		free(UNCONST(pattern.lhs));
3077 		free(UNCONST(pattern.rhs));
3078 		delim = '\0';
3079 		break;
3080 	    }
3081 	case '?':
3082 	    {
3083 		VarPattern 	pattern;
3084 		Boolean	value;
3085 
3086 		/* find ':', and then substitute accordingly */
3087 
3088 		pattern.flags = 0;
3089 
3090 		cp = ++tstr;
3091 		delim = ':';
3092 		if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3093 						 &cp, delim, NULL,
3094 						 &pattern.leftLen,
3095 						 NULL)) == NULL)
3096 		    goto cleanup;
3097 
3098 		/* BROPEN or PROPEN */
3099 		delim = endc;
3100 		if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3101 						 &cp, delim, NULL,
3102 						 &pattern.rightLen,
3103 						 NULL)) == NULL)
3104 		    goto cleanup;
3105 
3106 		termc = *--cp;
3107 		delim = '\0';
3108 		if (Cond_EvalExpression(NULL, v->name, &value, 0)
3109 		    == COND_INVALID) {
3110 		    Error("Bad conditional expression `%s' in %s?%s:%s",
3111 			  v->name, v->name, pattern.lhs, pattern.rhs);
3112 		    goto cleanup;
3113 		}
3114 
3115 		if (value) {
3116 		    newStr = UNCONST(pattern.lhs);
3117 		    free(UNCONST(pattern.rhs));
3118 		} else {
3119 		    newStr = UNCONST(pattern.rhs);
3120 		    free(UNCONST(pattern.lhs));
3121 		}
3122 		if (v->flags & VAR_JUNK) {
3123 		    v->flags |= VAR_KEEP;
3124 		}
3125 		break;
3126 	    }
3127 #ifndef NO_REGEX
3128 	case 'C':
3129 	    {
3130 		VarREPattern    pattern;
3131 		char           *re;
3132 		int             error;
3133 		Var_Parse_State tmpparsestate;
3134 
3135 		pattern.flags = 0;
3136 		tmpparsestate = parsestate;
3137 		delim = tstr[1];
3138 		tstr += 2;
3139 
3140 		cp = tstr;
3141 
3142 		if ((re = VarGetPattern(ctxt, &parsestate, errnum, &cp, delim,
3143 					NULL, NULL, NULL)) == NULL)
3144 		    goto cleanup;
3145 
3146 		if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
3147 						     errnum, &cp, delim, NULL,
3148 						     NULL, NULL)) == NULL){
3149 		    free(re);
3150 		    goto cleanup;
3151 		}
3152 
3153 		for (;; cp++) {
3154 		    switch (*cp) {
3155 		    case 'g':
3156 			pattern.flags |= VAR_SUB_GLOBAL;
3157 			continue;
3158 		    case '1':
3159 			pattern.flags |= VAR_SUB_ONE;
3160 			continue;
3161 		    case 'W':
3162 			tmpparsestate.oneBigWord = TRUE;
3163 			continue;
3164 		    }
3165 		    break;
3166 		}
3167 
3168 		termc = *cp;
3169 
3170 		error = regcomp(&pattern.re, re, REG_EXTENDED);
3171 		free(re);
3172 		if (error)  {
3173 		    *lengthPtr = cp - start + 1;
3174 		    VarREError(error, &pattern.re, "RE substitution error");
3175 		    free(pattern.replace);
3176 		    goto cleanup;
3177 		}
3178 
3179 		pattern.nsub = pattern.re.re_nsub + 1;
3180 		if (pattern.nsub < 1)
3181 		    pattern.nsub = 1;
3182 		if (pattern.nsub > 10)
3183 		    pattern.nsub = 10;
3184 		pattern.matches = bmake_malloc(pattern.nsub *
3185 					  sizeof(regmatch_t));
3186 		newStr = VarModify(ctxt, &tmpparsestate, nstr,
3187 				   VarRESubstitute,
3188 				   &pattern);
3189 		regfree(&pattern.re);
3190 		free(pattern.replace);
3191 		free(pattern.matches);
3192 		delim = '\0';
3193 		break;
3194 	    }
3195 #endif
3196 	case 'Q':
3197 	    if (tstr[1] == endc || tstr[1] == ':') {
3198 		newStr = VarQuote(nstr);
3199 		cp = tstr + 1;
3200 		termc = *cp;
3201 		break;
3202 	    }
3203 	    goto default_case;
3204 	case 'T':
3205 	    if (tstr[1] == endc || tstr[1] == ':') {
3206 		newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
3207 				   NULL);
3208 		cp = tstr + 1;
3209 		termc = *cp;
3210 		break;
3211 	    }
3212 	    goto default_case;
3213 	case 'H':
3214 	    if (tstr[1] == endc || tstr[1] == ':') {
3215 		newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
3216 				   NULL);
3217 		cp = tstr + 1;
3218 		termc = *cp;
3219 		break;
3220 	    }
3221 	    goto default_case;
3222 	case 'E':
3223 	    if (tstr[1] == endc || tstr[1] == ':') {
3224 		newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
3225 				   NULL);
3226 		cp = tstr + 1;
3227 		termc = *cp;
3228 		break;
3229 	    }
3230 	    goto default_case;
3231 	case 'R':
3232 	    if (tstr[1] == endc || tstr[1] == ':') {
3233 		newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
3234 				   NULL);
3235 		cp = tstr + 1;
3236 		termc = *cp;
3237 		break;
3238 	    }
3239 	    goto default_case;
3240 	case 'O':
3241 	    {
3242 		char otype;
3243 
3244 		cp = tstr + 1;	/* skip to the rest in any case */
3245 		if (tstr[1] == endc || tstr[1] == ':') {
3246 		    otype = 's';
3247 		    termc = *cp;
3248 		} else if ( (tstr[1] == 'x') &&
3249 			    (tstr[2] == endc || tstr[2] == ':') ) {
3250 		    otype = tstr[1];
3251 		    cp = tstr + 2;
3252 		    termc = *cp;
3253 		} else {
3254 		    goto bad_modifier;
3255 		}
3256 		newStr = VarOrder(nstr, otype);
3257 		break;
3258 	    }
3259 	case 'u':
3260 	    if (tstr[1] == endc || tstr[1] == ':') {
3261 		newStr = VarUniq(nstr);
3262 		cp = tstr + 1;
3263 		termc = *cp;
3264 		break;
3265 	    }
3266 	    goto default_case;
3267 #ifdef SUNSHCMD
3268 	case 's':
3269 	    if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
3270 		const char *emsg;
3271 		newStr = Cmd_Exec(nstr, &emsg);
3272 		if (emsg)
3273 		    Error(emsg, nstr);
3274 		cp = tstr + 2;
3275 		termc = *cp;
3276 		break;
3277 	    }
3278 	    goto default_case;
3279 #endif
3280 	default:
3281 	default_case:
3282 	{
3283 #ifdef SYSVVARSUB
3284 	    /*
3285 	     * This can either be a bogus modifier or a System-V
3286 	     * substitution command.
3287 	     */
3288 	    VarPattern      pattern;
3289 	    Boolean         eqFound;
3290 
3291 	    pattern.flags = 0;
3292 	    eqFound = FALSE;
3293 	    /*
3294 	     * First we make a pass through the string trying
3295 	     * to verify it is a SYSV-make-style translation:
3296 	     * it must be: <string1>=<string2>)
3297 	     */
3298 	    cp = tstr;
3299 	    cnt = 1;
3300 	    while (*cp != '\0' && cnt) {
3301 		if (*cp == '=') {
3302 		    eqFound = TRUE;
3303 		    /* continue looking for endc */
3304 		}
3305 		else if (*cp == endc)
3306 		    cnt--;
3307 		else if (*cp == startc)
3308 		    cnt++;
3309 		if (cnt)
3310 		    cp++;
3311 	    }
3312 	    if (*cp == endc && eqFound) {
3313 
3314 		/*
3315 		 * Now we break this sucker into the lhs and
3316 		 * rhs. We must null terminate them of course.
3317 		 */
3318 		delim='=';
3319 		cp = tstr;
3320 		if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
3321 						 errnum, &cp, delim, &pattern.flags,
3322 						 &pattern.leftLen, NULL)) == NULL)
3323 		    goto cleanup;
3324 		delim = endc;
3325 		if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
3326 						 errnum, &cp, delim, NULL, &pattern.rightLen,
3327 						 &pattern)) == NULL)
3328 		    goto cleanup;
3329 
3330 		/*
3331 		 * SYSV modifications happen through the whole
3332 		 * string. Note the pattern is anchored at the end.
3333 		 */
3334 		termc = *--cp;
3335 		delim = '\0';
3336 		newStr = VarModify(ctxt, &parsestate, nstr,
3337 				   VarSYSVMatch,
3338 				   &pattern);
3339 		free(UNCONST(pattern.lhs));
3340 		free(UNCONST(pattern.rhs));
3341 	    } else
3342 #endif
3343 		{
3344 		    Error("Unknown modifier '%c'", *tstr);
3345 		    for (cp = tstr+1;
3346 			 *cp != ':' && *cp != endc && *cp != '\0';
3347 			 cp++)
3348 			continue;
3349 		    termc = *cp;
3350 		    newStr = var_Error;
3351 		}
3352 	    }
3353 	}
3354 	if (DEBUG(VAR)) {
3355 	    fprintf(debug_file, "Result of :%c is \"%s\"\n", modifier, newStr);
3356 	}
3357 
3358 	if (newStr != nstr) {
3359 	    if (*freePtr) {
3360 		free(nstr);
3361 		*freePtr = NULL;
3362 	    }
3363 	    nstr = newStr;
3364 	    if (nstr != var_Error && nstr != varNoError) {
3365 		*freePtr = nstr;
3366 	    }
3367 	}
3368 	if (termc == '\0' && endc != '\0') {
3369 	    Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier);
3370 	} else if (termc == ':') {
3371 	    cp++;
3372 	}
3373 	tstr = cp;
3374     }
3375  out:
3376     *lengthPtr = tstr - start;
3377     return (nstr);
3378 
3379  bad_modifier:
3380     /* "{(" */
3381     Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
3382 	  v->name);
3383 
3384  cleanup:
3385     *lengthPtr = cp - start;
3386     if (delim != '\0')
3387 	Error("Unclosed substitution for %s (%c missing)",
3388 	      v->name, delim);
3389     if (*freePtr) {
3390 	free(*freePtr);
3391 	*freePtr = NULL;
3392     }
3393     return (var_Error);
3394 }
3395 
3396 /*-
3397  *-----------------------------------------------------------------------
3398  * Var_Parse --
3399  *	Given the start of a variable invocation, extract the variable
3400  *	name and find its value, then modify it according to the
3401  *	specification.
3402  *
3403  * Input:
3404  *	str		The string to parse
3405  *	ctxt		The context for the variable
3406  *	errnum		TRUE if undefined variables are an error
3407  *	lengthPtr	OUT: The length of the specification
3408  *	freePtr		OUT: Non-NULL if caller should free *freePtr
3409  *
3410  * Results:
3411  *	The (possibly-modified) value of the variable or var_Error if the
3412  *	specification is invalid. The length of the specification is
3413  *	placed in *lengthPtr (for invalid specifications, this is just
3414  *	2...?).
3415  *	If *freePtr is non-NULL then it's a pointer that the caller
3416  *	should pass to free() to free memory used by the result.
3417  *
3418  * Side Effects:
3419  *	None.
3420  *
3421  *-----------------------------------------------------------------------
3422  */
3423 /* coverity[+alloc : arg-*4] */
3424 char *
3425 Var_Parse(const char *str, GNode *ctxt, Boolean errnum, int *lengthPtr,
3426 	  void **freePtr)
3427 {
3428     const char	   *tstr;    	/* Pointer into str */
3429     Var		   *v;		/* Variable in invocation */
3430     Boolean 	    haveModifier;/* TRUE if have modifiers for the variable */
3431     char	    endc;    	/* Ending character when variable in parens
3432 				 * or braces */
3433     char	    startc;	/* Starting character when variable in parens
3434 				 * or braces */
3435     int		    vlen;	/* Length of variable name */
3436     const char 	   *start;	/* Points to original start of str */
3437     char	   *nstr;	/* New string, used during expansion */
3438     Boolean 	    dynamic;	/* TRUE if the variable is local and we're
3439 				 * expanding it in a non-local context. This
3440 				 * is done to support dynamic sources. The
3441 				 * result is just the invocation, unaltered */
3442     Var_Parse_State parsestate; /* Flags passed to helper functions */
3443     char	  name[2];
3444 
3445     *freePtr = NULL;
3446     dynamic = FALSE;
3447     start = str;
3448     parsestate.oneBigWord = FALSE;
3449     parsestate.varSpace = ' ';	/* word separator */
3450 
3451     startc = str[1];
3452     if (startc != PROPEN && startc != BROPEN) {
3453 	/*
3454 	 * If it's not bounded by braces of some sort, life is much simpler.
3455 	 * We just need to check for the first character and return the
3456 	 * value if it exists.
3457 	 */
3458 
3459 	/* Error out some really stupid names */
3460 	if (startc == '\0' || strchr(")}:$", startc)) {
3461 	    *lengthPtr = 1;
3462 	    return var_Error;
3463 	}
3464 	name[0] = startc;
3465 	name[1] = '\0';
3466 
3467 	v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3468 	if (v == NULL) {
3469 	    *lengthPtr = 2;
3470 
3471 	    if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
3472 		/*
3473 		 * If substituting a local variable in a non-local context,
3474 		 * assume it's for dynamic source stuff. We have to handle
3475 		 * this specially and return the longhand for the variable
3476 		 * with the dollar sign escaped so it makes it back to the
3477 		 * caller. Only four of the local variables are treated
3478 		 * specially as they are the only four that will be set
3479 		 * when dynamic sources are expanded.
3480 		 */
3481 		switch (str[1]) {
3482 		    case '@':
3483 			return UNCONST("$(.TARGET)");
3484 		    case '%':
3485 			return UNCONST("$(.ARCHIVE)");
3486 		    case '*':
3487 			return UNCONST("$(.PREFIX)");
3488 		    case '!':
3489 			return UNCONST("$(.MEMBER)");
3490 		}
3491 	    }
3492 	    /*
3493 	     * Error
3494 	     */
3495 	    return (errnum ? var_Error : varNoError);
3496 	} else {
3497 	    haveModifier = FALSE;
3498 	    tstr = &str[1];
3499 	    endc = str[1];
3500 	}
3501     } else {
3502 	Buffer buf;	/* Holds the variable name */
3503 
3504 	endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3505 	Buf_Init(&buf, 0);
3506 
3507 	/*
3508 	 * Skip to the end character or a colon, whichever comes first.
3509 	 */
3510 	for (tstr = str + 2;
3511 	     *tstr != '\0' && *tstr != endc && *tstr != ':';
3512 	     tstr++)
3513 	{
3514 	    /*
3515 	     * A variable inside a variable, expand
3516 	     */
3517 	    if (*tstr == '$') {
3518 		int rlen;
3519 		void *freeIt;
3520 		char *rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
3521 		if (rval != NULL) {
3522 		    Buf_AddBytes(&buf, strlen(rval), rval);
3523 		}
3524 		if (freeIt)
3525 		    free(freeIt);
3526 		tstr += rlen - 1;
3527 	    }
3528 	    else
3529 		Buf_AddByte(&buf, *tstr);
3530 	}
3531 	if (*tstr == ':') {
3532 	    haveModifier = TRUE;
3533 	} else if (*tstr != '\0') {
3534 	    haveModifier = FALSE;
3535 	} else {
3536 	    /*
3537 	     * If we never did find the end character, return NULL
3538 	     * right now, setting the length to be the distance to
3539 	     * the end of the string, since that's what make does.
3540 	     */
3541 	    *lengthPtr = tstr - str;
3542 	    Buf_Destroy(&buf, TRUE);
3543 	    return (var_Error);
3544 	}
3545 	str = Buf_GetAll(&buf, &vlen);
3546 
3547 	/*
3548 	 * At this point, str points into newly allocated memory from
3549 	 * buf, containing only the name of the variable.
3550 	 *
3551 	 * start and tstr point into the const string that was pointed
3552 	 * to by the original value of the str parameter.  start points
3553 	 * to the '$' at the beginning of the string, while tstr points
3554 	 * to the char just after the end of the variable name -- this
3555 	 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3556 	 */
3557 
3558 	v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3559 	/*
3560 	 * Check also for bogus D and F forms of local variables since we're
3561 	 * in a local context and the name is the right length.
3562 	 */
3563 	if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
3564 		(vlen == 2) && (str[1] == 'F' || str[1] == 'D') &&
3565 		strchr("@%*!<>", str[0]) != NULL) {
3566 	    /*
3567 	     * Well, it's local -- go look for it.
3568 	     */
3569 	    name[0] = *str;
3570 	    name[1] = '\0';
3571 	    v = VarFind(name, ctxt, 0);
3572 
3573 	    if (v != NULL) {
3574 		/*
3575 		 * No need for nested expansion or anything, as we're
3576 		 * the only one who sets these things and we sure don't
3577 		 * but nested invocations in them...
3578 		 */
3579 		nstr = Buf_GetAll(&v->val, NULL);
3580 
3581 		if (str[1] == 'D') {
3582 		    nstr = VarModify(ctxt, &parsestate, nstr, VarHead,
3583 				    NULL);
3584 		} else {
3585 		    nstr = VarModify(ctxt, &parsestate, nstr, VarTail,
3586 				    NULL);
3587 		}
3588 		/*
3589 		 * Resulting string is dynamically allocated, so
3590 		 * tell caller to free it.
3591 		 */
3592 		*freePtr = nstr;
3593 		*lengthPtr = tstr-start+1;
3594 		Buf_Destroy(&buf, TRUE);
3595 		VarFreeEnv(v, TRUE);
3596 		return nstr;
3597 	    }
3598 	}
3599 
3600 	if (v == NULL) {
3601 	    if (((vlen == 1) ||
3602 		 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
3603 		((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3604 	    {
3605 		/*
3606 		 * If substituting a local variable in a non-local context,
3607 		 * assume it's for dynamic source stuff. We have to handle
3608 		 * this specially and return the longhand for the variable
3609 		 * with the dollar sign escaped so it makes it back to the
3610 		 * caller. Only four of the local variables are treated
3611 		 * specially as they are the only four that will be set
3612 		 * when dynamic sources are expanded.
3613 		 */
3614 		switch (*str) {
3615 		    case '@':
3616 		    case '%':
3617 		    case '*':
3618 		    case '!':
3619 			dynamic = TRUE;
3620 			break;
3621 		}
3622 	    } else if ((vlen > 2) && (*str == '.') &&
3623 		       isupper((unsigned char) str[1]) &&
3624 		       ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3625 	    {
3626 		int	len;
3627 
3628 		len = vlen - 1;
3629 		if ((strncmp(str, ".TARGET", len) == 0) ||
3630 		    (strncmp(str, ".ARCHIVE", len) == 0) ||
3631 		    (strncmp(str, ".PREFIX", len) == 0) ||
3632 		    (strncmp(str, ".MEMBER", len) == 0))
3633 		{
3634 		    dynamic = TRUE;
3635 		}
3636 	    }
3637 
3638 	    if (!haveModifier) {
3639 		/*
3640 		 * No modifiers -- have specification length so we can return
3641 		 * now.
3642 		 */
3643 		*lengthPtr = tstr - start + 1;
3644 		if (dynamic) {
3645 		    char *pstr = bmake_strndup(start, *lengthPtr);
3646 		    *freePtr = pstr;
3647 		    Buf_Destroy(&buf, TRUE);
3648 		    return(pstr);
3649 		} else {
3650 		    Buf_Destroy(&buf, TRUE);
3651 		    return (errnum ? var_Error : varNoError);
3652 		}
3653 	    } else {
3654 		/*
3655 		 * Still need to get to the end of the variable specification,
3656 		 * so kludge up a Var structure for the modifications
3657 		 */
3658 		v = bmake_malloc(sizeof(Var));
3659 		v->name = UNCONST(str);
3660 		Buf_Init(&v->val, 1);
3661 		v->flags = VAR_JUNK;
3662 		Buf_Destroy(&buf, FALSE);
3663 	    }
3664 	} else
3665 	    Buf_Destroy(&buf, TRUE);
3666     }
3667 
3668     if (v->flags & VAR_IN_USE) {
3669 	Fatal("Variable %s is recursive.", v->name);
3670 	/*NOTREACHED*/
3671     } else {
3672 	v->flags |= VAR_IN_USE;
3673     }
3674     /*
3675      * Before doing any modification, we have to make sure the value
3676      * has been fully expanded. If it looks like recursion might be
3677      * necessary (there's a dollar sign somewhere in the variable's value)
3678      * we just call Var_Subst to do any other substitutions that are
3679      * necessary. Note that the value returned by Var_Subst will have
3680      * been dynamically-allocated, so it will need freeing when we
3681      * return.
3682      */
3683     nstr = Buf_GetAll(&v->val, NULL);
3684     if (strchr(nstr, '$') != NULL) {
3685 	nstr = Var_Subst(NULL, nstr, ctxt, errnum);
3686 	*freePtr = nstr;
3687     }
3688 
3689     v->flags &= ~VAR_IN_USE;
3690 
3691     if ((nstr != NULL) && haveModifier) {
3692 	int used;
3693 	/*
3694 	 * Skip initial colon.
3695 	 */
3696 	tstr++;
3697 
3698 	nstr = ApplyModifiers(nstr, tstr, startc, endc,
3699 			      v, ctxt, errnum, &used, freePtr);
3700 	tstr += used;
3701     }
3702     if (*tstr) {
3703 	*lengthPtr = tstr - start + 1;
3704     } else {
3705 	*lengthPtr = tstr - start;
3706     }
3707 
3708     if (v->flags & VAR_FROM_ENV) {
3709 	Boolean	  destroy = FALSE;
3710 
3711 	if (nstr != Buf_GetAll(&v->val, NULL)) {
3712 	    destroy = TRUE;
3713 	} else {
3714 	    /*
3715 	     * Returning the value unmodified, so tell the caller to free
3716 	     * the thing.
3717 	     */
3718 	    *freePtr = nstr;
3719 	}
3720 	VarFreeEnv(v, destroy);
3721     } else if (v->flags & VAR_JUNK) {
3722 	/*
3723 	 * Perform any free'ing needed and set *freePtr to NULL so the caller
3724 	 * doesn't try to free a static pointer.
3725 	 * If VAR_KEEP is also set then we want to keep str as is.
3726 	 */
3727 	if (!(v->flags & VAR_KEEP)) {
3728 	    if (*freePtr) {
3729 		free(nstr);
3730 		*freePtr = NULL;
3731 	    }
3732 	    if (dynamic) {
3733 		nstr = bmake_strndup(start, *lengthPtr);
3734 		*freePtr = nstr;
3735 	    } else {
3736 		nstr = var_Error;
3737 	    }
3738 	}
3739 	if (nstr != Buf_GetAll(&v->val, NULL))
3740 	    Buf_Destroy(&v->val, TRUE);
3741 	free(v->name);
3742 	free(v);
3743     }
3744     return (nstr);
3745 }
3746 
3747 /*-
3748  *-----------------------------------------------------------------------
3749  * Var_Subst  --
3750  *	Substitute for all variables in the given string in the given context
3751  *	If undefErr is TRUE, Parse_Error will be called when an undefined
3752  *	variable is encountered.
3753  *
3754  * Input:
3755  *	var		Named variable || NULL for all
3756  *	str		the string which to substitute
3757  *	ctxt		the context wherein to find variables
3758  *	undefErr	TRUE if undefineds are an error
3759  *
3760  * Results:
3761  *	The resulting string.
3762  *
3763  * Side Effects:
3764  *	None. The old string must be freed by the caller
3765  *-----------------------------------------------------------------------
3766  */
3767 char *
3768 Var_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
3769 {
3770     Buffer  	  buf;		    /* Buffer for forming things */
3771     char    	  *val;		    /* Value to substitute for a variable */
3772     int		  length;   	    /* Length of the variable invocation */
3773     Boolean	  trailingBslash;   /* variable ends in \ */
3774     void 	  *freeIt = NULL;    /* Set if it should be freed */
3775     static Boolean errorReported;   /* Set true if an error has already
3776 				     * been reported to prevent a plethora
3777 				     * of messages when recursing */
3778 
3779     Buf_Init(&buf, 0);
3780     errorReported = FALSE;
3781     trailingBslash = FALSE;
3782 
3783     while (*str) {
3784 	if (*str == '\n' && trailingBslash)
3785 	    Buf_AddByte(&buf, ' ');
3786 	if (var == NULL && (*str == '$') && (str[1] == '$')) {
3787 	    /*
3788 	     * A dollar sign may be escaped either with another dollar sign.
3789 	     * In such a case, we skip over the escape character and store the
3790 	     * dollar sign into the buffer directly.
3791 	     */
3792 	    str++;
3793 	    Buf_AddByte(&buf, *str);
3794 	    str++;
3795 	} else if (*str != '$') {
3796 	    /*
3797 	     * Skip as many characters as possible -- either to the end of
3798 	     * the string or to the next dollar sign (variable invocation).
3799 	     */
3800 	    const char  *cp;
3801 
3802 	    for (cp = str++; *str != '$' && *str != '\0'; str++)
3803 		continue;
3804 	    Buf_AddBytes(&buf, str - cp, cp);
3805 	} else {
3806 	    if (var != NULL) {
3807 		int expand;
3808 		for (;;) {
3809 		    if (str[1] == '\0') {
3810 			/* A trailing $ is kind of a special case */
3811 			Buf_AddByte(&buf, str[0]);
3812 			str++;
3813 			expand = FALSE;
3814 		    } else if (str[1] != PROPEN && str[1] != BROPEN) {
3815 			if (str[1] != *var || strlen(var) > 1) {
3816 			    Buf_AddBytes(&buf, 2, str);
3817 			    str += 2;
3818 			    expand = FALSE;
3819 			}
3820 			else
3821 			    expand = TRUE;
3822 			break;
3823 		    }
3824 		    else {
3825 			const char *p;
3826 
3827 			/*
3828 			 * Scan up to the end of the variable name.
3829 			 */
3830 			for (p = &str[2]; *p &&
3831 			     *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
3832 			    if (*p == '$')
3833 				break;
3834 			/*
3835 			 * A variable inside the variable. We cannot expand
3836 			 * the external variable yet, so we try again with
3837 			 * the nested one
3838 			 */
3839 			if (*p == '$') {
3840 			    Buf_AddBytes(&buf, p - str, str);
3841 			    str = p;
3842 			    continue;
3843 			}
3844 
3845 			if (strncmp(var, str + 2, p - str - 2) != 0 ||
3846 			    var[p - str - 2] != '\0') {
3847 			    /*
3848 			     * Not the variable we want to expand, scan
3849 			     * until the next variable
3850 			     */
3851 			    for (;*p != '$' && *p != '\0'; p++)
3852 				continue;
3853 			    Buf_AddBytes(&buf, p - str, str);
3854 			    str = p;
3855 			    expand = FALSE;
3856 			}
3857 			else
3858 			    expand = TRUE;
3859 			break;
3860 		    }
3861 		}
3862 		if (!expand)
3863 		    continue;
3864 	    }
3865 
3866 	    val = Var_Parse(str, ctxt, undefErr, &length, &freeIt);
3867 
3868 	    /*
3869 	     * When we come down here, val should either point to the
3870 	     * value of this variable, suitably modified, or be NULL.
3871 	     * Length should be the total length of the potential
3872 	     * variable invocation (from $ to end character...)
3873 	     */
3874 	    if (val == var_Error || val == varNoError) {
3875 		/*
3876 		 * If performing old-time variable substitution, skip over
3877 		 * the variable and continue with the substitution. Otherwise,
3878 		 * store the dollar sign and advance str so we continue with
3879 		 * the string...
3880 		 */
3881 		if (oldVars) {
3882 		    str += length;
3883 		} else if (undefErr) {
3884 		    /*
3885 		     * If variable is undefined, complain and skip the
3886 		     * variable. The complaint will stop us from doing anything
3887 		     * when the file is parsed.
3888 		     */
3889 		    if (!errorReported) {
3890 			Parse_Error(PARSE_FATAL,
3891 				     "Undefined variable \"%.*s\"",length,str);
3892 		    }
3893 		    str += length;
3894 		    errorReported = TRUE;
3895 		} else {
3896 		    Buf_AddByte(&buf, *str);
3897 		    str += 1;
3898 		}
3899 	    } else {
3900 		/*
3901 		 * We've now got a variable structure to store in. But first,
3902 		 * advance the string pointer.
3903 		 */
3904 		str += length;
3905 
3906 		/*
3907 		 * Copy all the characters from the variable value straight
3908 		 * into the new string.
3909 		 */
3910 		length = strlen(val);
3911 		Buf_AddBytes(&buf, length, val);
3912 		trailingBslash = length > 0 && val[length - 1] == '\\';
3913 	    }
3914 	    if (freeIt) {
3915 		free(freeIt);
3916 		freeIt = NULL;
3917 	    }
3918 	}
3919     }
3920 
3921     return Buf_Destroy(&buf, FALSE);
3922 }
3923 
3924 /*-
3925  *-----------------------------------------------------------------------
3926  * Var_GetTail --
3927  *	Return the tail from each of a list of words. Used to set the
3928  *	System V local variables.
3929  *
3930  * Input:
3931  *	file		Filename to modify
3932  *
3933  * Results:
3934  *	The resulting string.
3935  *
3936  * Side Effects:
3937  *	None.
3938  *
3939  *-----------------------------------------------------------------------
3940  */
3941 #if 0
3942 char *
3943 Var_GetTail(char *file)
3944 {
3945     return(VarModify(file, VarTail, NULL));
3946 }
3947 
3948 /*-
3949  *-----------------------------------------------------------------------
3950  * Var_GetHead --
3951  *	Find the leading components of a (list of) filename(s).
3952  *	XXX: VarHead does not replace foo by ., as (sun) System V make
3953  *	does.
3954  *
3955  * Input:
3956  *	file		Filename to manipulate
3957  *
3958  * Results:
3959  *	The leading components.
3960  *
3961  * Side Effects:
3962  *	None.
3963  *
3964  *-----------------------------------------------------------------------
3965  */
3966 char *
3967 Var_GetHead(char *file)
3968 {
3969     return(VarModify(file, VarHead, NULL));
3970 }
3971 #endif
3972 
3973 /*-
3974  *-----------------------------------------------------------------------
3975  * Var_Init --
3976  *	Initialize the module
3977  *
3978  * Results:
3979  *	None
3980  *
3981  * Side Effects:
3982  *	The VAR_CMD and VAR_GLOBAL contexts are created
3983  *-----------------------------------------------------------------------
3984  */
3985 void
3986 Var_Init(void)
3987 {
3988     VAR_GLOBAL = Targ_NewGN("Global");
3989     VAR_CMD = Targ_NewGN("Command");
3990 
3991 }
3992 
3993 
3994 void
3995 Var_End(void)
3996 {
3997 }
3998 
3999 
4000 /****************** PRINT DEBUGGING INFO *****************/
4001 static void
4002 VarPrintVar(void *vp)
4003 {
4004     Var    *v = (Var *)vp;
4005     fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
4006 }
4007 
4008 /*-
4009  *-----------------------------------------------------------------------
4010  * Var_Dump --
4011  *	print all variables in a context
4012  *-----------------------------------------------------------------------
4013  */
4014 void
4015 Var_Dump(GNode *ctxt)
4016 {
4017     Hash_Search search;
4018     Hash_Entry *h;
4019 
4020     for (h = Hash_EnumFirst(&ctxt->context, &search);
4021 	 h != NULL;
4022 	 h = Hash_EnumNext(&search)) {
4023 	    VarPrintVar(Hash_GetValue(h));
4024     }
4025 }
4026