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