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