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