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