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