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