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