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