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