var.c revision 250164
1249033Ssjg/*	$NetBSD: var.c,v 1.173 2013/02/24 19:43:37 christos Exp $	*/
2236769Sobrien
3236769Sobrien/*
4236769Sobrien * Copyright (c) 1988, 1989, 1990, 1993
5236769Sobrien *	The Regents of the University of California.  All rights reserved.
6236769Sobrien *
7236769Sobrien * This code is derived from software contributed to Berkeley by
8236769Sobrien * Adam de Boor.
9236769Sobrien *
10236769Sobrien * Redistribution and use in source and binary forms, with or without
11236769Sobrien * modification, are permitted provided that the following conditions
12236769Sobrien * are met:
13236769Sobrien * 1. Redistributions of source code must retain the above copyright
14236769Sobrien *    notice, this list of conditions and the following disclaimer.
15236769Sobrien * 2. Redistributions in binary form must reproduce the above copyright
16236769Sobrien *    notice, this list of conditions and the following disclaimer in the
17236769Sobrien *    documentation and/or other materials provided with the distribution.
18236769Sobrien * 3. Neither the name of the University nor the names of its contributors
19236769Sobrien *    may be used to endorse or promote products derived from this software
20236769Sobrien *    without specific prior written permission.
21236769Sobrien *
22236769Sobrien * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23236769Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24236769Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25236769Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26236769Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27236769Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28236769Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29236769Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30236769Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31236769Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32236769Sobrien * SUCH DAMAGE.
33236769Sobrien */
34236769Sobrien
35236769Sobrien/*
36236769Sobrien * Copyright (c) 1989 by Berkeley Softworks
37236769Sobrien * All rights reserved.
38236769Sobrien *
39236769Sobrien * This code is derived from software contributed to Berkeley by
40236769Sobrien * Adam de Boor.
41236769Sobrien *
42236769Sobrien * Redistribution and use in source and binary forms, with or without
43236769Sobrien * modification, are permitted provided that the following conditions
44236769Sobrien * are met:
45236769Sobrien * 1. Redistributions of source code must retain the above copyright
46236769Sobrien *    notice, this list of conditions and the following disclaimer.
47236769Sobrien * 2. Redistributions in binary form must reproduce the above copyright
48236769Sobrien *    notice, this list of conditions and the following disclaimer in the
49236769Sobrien *    documentation and/or other materials provided with the distribution.
50236769Sobrien * 3. All advertising materials mentioning features or use of this software
51236769Sobrien *    must display the following acknowledgement:
52236769Sobrien *	This product includes software developed by the University of
53236769Sobrien *	California, Berkeley and its contributors.
54236769Sobrien * 4. Neither the name of the University nor the names of its contributors
55236769Sobrien *    may be used to endorse or promote products derived from this software
56236769Sobrien *    without specific prior written permission.
57236769Sobrien *
58236769Sobrien * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59236769Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60236769Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61236769Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62236769Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63236769Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64236769Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65236769Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66236769Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67236769Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68236769Sobrien * SUCH DAMAGE.
69236769Sobrien */
70236769Sobrien
71236769Sobrien#ifndef MAKE_NATIVE
72249033Ssjgstatic char rcsid[] = "$NetBSD: var.c,v 1.173 2013/02/24 19:43:37 christos Exp $";
73236769Sobrien#else
74236769Sobrien#include <sys/cdefs.h>
75236769Sobrien#ifndef lint
76236769Sobrien#if 0
77236769Sobrienstatic char sccsid[] = "@(#)var.c	8.3 (Berkeley) 3/19/94";
78236769Sobrien#else
79249033Ssjg__RCSID("$NetBSD: var.c,v 1.173 2013/02/24 19:43:37 christos Exp $");
80236769Sobrien#endif
81236769Sobrien#endif /* not lint */
82236769Sobrien#endif
83236769Sobrien
84236769Sobrien/*-
85236769Sobrien * var.c --
86236769Sobrien *	Variable-handling functions
87236769Sobrien *
88236769Sobrien * Interface:
89236769Sobrien *	Var_Set		    Set the value of a variable in the given
90236769Sobrien *			    context. The variable is created if it doesn't
91236769Sobrien *			    yet exist. The value and variable name need not
92236769Sobrien *			    be preserved.
93236769Sobrien *
94236769Sobrien *	Var_Append	    Append more characters to an existing variable
95236769Sobrien *			    in the given context. The variable needn't
96236769Sobrien *			    exist already -- it will be created if it doesn't.
97236769Sobrien *			    A space is placed between the old value and the
98236769Sobrien *			    new one.
99236769Sobrien *
100236769Sobrien *	Var_Exists	    See if a variable exists.
101236769Sobrien *
102236769Sobrien *	Var_Value 	    Return the value of a variable in a context or
103236769Sobrien *			    NULL if the variable is undefined.
104236769Sobrien *
105236769Sobrien *	Var_Subst 	    Substitute named variable, or all variables if
106236769Sobrien *			    NULL in a string using
107236769Sobrien *			    the given context as the top-most one. If the
108236769Sobrien *			    third argument is non-zero, Parse_Error is
109236769Sobrien *			    called if any variables are undefined.
110236769Sobrien *
111236769Sobrien *	Var_Parse 	    Parse a variable expansion from a string and
112236769Sobrien *			    return the result and the number of characters
113236769Sobrien *			    consumed.
114236769Sobrien *
115236769Sobrien *	Var_Delete	    Delete a variable in a context.
116236769Sobrien *
117236769Sobrien *	Var_Init  	    Initialize this module.
118236769Sobrien *
119236769Sobrien * Debugging:
120236769Sobrien *	Var_Dump  	    Print out all variables defined in the given
121236769Sobrien *			    context.
122236769Sobrien *
123236769Sobrien * XXX: There's a lot of duplication in these functions.
124236769Sobrien */
125236769Sobrien
126236769Sobrien#include    <sys/stat.h>
127236769Sobrien#ifndef NO_REGEX
128236769Sobrien#include    <sys/types.h>
129236769Sobrien#include    <regex.h>
130236769Sobrien#endif
131236769Sobrien#include    <ctype.h>
132236769Sobrien#include    <inttypes.h>
133236769Sobrien#include    <stdlib.h>
134236769Sobrien#include    <limits.h>
135236769Sobrien#include    <time.h>
136236769Sobrien
137236769Sobrien#include    "make.h"
138236769Sobrien#include    "buf.h"
139236769Sobrien#include    "dir.h"
140236769Sobrien#include    "job.h"
141236769Sobrien
142236769Sobrien/*
143250164Ssjg * XXX transition hack for FreeBSD ports.
144250164Ssjg * bsd.port.mk can set .MAKE.FreeBSD_UL=yes
145250164Ssjg * to cause us to treat :[LU] as aliases for :t[lu]
146250164Ssjg * To be reverted when ports converts to :t[lu] (when 8.3 is EOL)
147250164Ssjg */
148250164Ssjg#define MAKE_FREEBSD_UL ".MAKE.FreeBSD_UL"
149250164Ssjg#ifdef MAKE_FREEBSD_UL
150250164Ssjgstatic int FreeBSD_UL = FALSE;
151250164Ssjg#endif
152250164Ssjg
153250164Ssjg/*
154236769Sobrien * This lets us tell if we have replaced the original environ
155236769Sobrien * (which we cannot free).
156236769Sobrien */
157236769Sobrienchar **savedEnv = NULL;
158236769Sobrien
159236769Sobrien/*
160236769Sobrien * This is a harmless return value for Var_Parse that can be used by Var_Subst
161236769Sobrien * to determine if there was an error in parsing -- easier than returning
162236769Sobrien * a flag, as things outside this module don't give a hoot.
163236769Sobrien */
164236769Sobrienchar 	var_Error[] = "";
165236769Sobrien
166236769Sobrien/*
167236769Sobrien * Similar to var_Error, but returned when the 'errnum' flag for Var_Parse is
168236769Sobrien * set false. Why not just use a constant? Well, gcc likes to condense
169236769Sobrien * identical string instances...
170236769Sobrien */
171236769Sobrienstatic char	varNoError[] = "";
172236769Sobrien
173236769Sobrien/*
174236769Sobrien * Internally, variables are contained in four different contexts.
175236769Sobrien *	1) the environment. They may not be changed. If an environment
176236769Sobrien *	    variable is appended-to, the result is placed in the global
177236769Sobrien *	    context.
178236769Sobrien *	2) the global context. Variables set in the Makefile are located in
179236769Sobrien *	    the global context. It is the penultimate context searched when
180236769Sobrien *	    substituting.
181236769Sobrien *	3) the command-line context. All variables set on the command line
182236769Sobrien *	   are placed in this context. They are UNALTERABLE once placed here.
183236769Sobrien *	4) the local context. Each target has associated with it a context
184236769Sobrien *	   list. On this list are located the structures describing such
185236769Sobrien *	   local variables as $(@) and $(*)
186236769Sobrien * The four contexts are searched in the reverse order from which they are
187236769Sobrien * listed.
188236769Sobrien */
189236769SobrienGNode          *VAR_GLOBAL;   /* variables from the makefile */
190236769SobrienGNode          *VAR_CMD;      /* variables defined on the command-line */
191236769Sobrien
192236769Sobrien#define FIND_CMD	0x1   /* look in VAR_CMD when searching */
193236769Sobrien#define FIND_GLOBAL	0x2   /* look in VAR_GLOBAL as well */
194236769Sobrien#define FIND_ENV  	0x4   /* look in the environment also */
195236769Sobrien
196236769Sobrientypedef struct Var {
197236769Sobrien    char          *name;	/* the variable's name */
198236769Sobrien    Buffer	  val;		/* its value */
199236769Sobrien    int		  flags;    	/* miscellaneous status flags */
200236769Sobrien#define VAR_IN_USE	1   	    /* Variable's value currently being used.
201236769Sobrien				     * Used to avoid recursion */
202236769Sobrien#define VAR_FROM_ENV	2   	    /* Variable comes from the environment */
203236769Sobrien#define VAR_JUNK  	4   	    /* Variable is a junk variable that
204236769Sobrien				     * should be destroyed when done with
205236769Sobrien				     * it. Used by Var_Parse for undefined,
206236769Sobrien				     * modified variables */
207236769Sobrien#define VAR_KEEP	8	    /* Variable is VAR_JUNK, but we found
208236769Sobrien				     * a use for it in some modifier and
209236769Sobrien				     * the value is therefore valid */
210236769Sobrien#define VAR_EXPORTED	16 	    /* Variable is exported */
211236769Sobrien#define VAR_REEXPORT	32	    /* Indicate if var needs re-export.
212236769Sobrien				     * This would be true if it contains $'s
213236769Sobrien				     */
214236769Sobrien#define VAR_FROM_CMD	64 	    /* Variable came from command line */
215236769Sobrien}  Var;
216236769Sobrien
217236769Sobrien/*
218236769Sobrien * Exporting vars is expensive so skip it if we can
219236769Sobrien */
220236769Sobrien#define VAR_EXPORTED_NONE	0
221236769Sobrien#define VAR_EXPORTED_YES	1
222236769Sobrien#define VAR_EXPORTED_ALL	2
223236769Sobrienstatic int var_exportedVars = VAR_EXPORTED_NONE;
224236769Sobrien/*
225236769Sobrien * We pass this to Var_Export when doing the initial export
226236769Sobrien * or after updating an exported var.
227236769Sobrien */
228236769Sobrien#define VAR_EXPORT_PARENT 1
229236769Sobrien
230236769Sobrien/* Var*Pattern flags */
231236769Sobrien#define VAR_SUB_GLOBAL	0x01	/* Apply substitution globally */
232236769Sobrien#define VAR_SUB_ONE	0x02	/* Apply substitution to one word */
233236769Sobrien#define VAR_SUB_MATCHED	0x04	/* There was a match */
234236769Sobrien#define VAR_MATCH_START	0x08	/* Match at start of word */
235236769Sobrien#define VAR_MATCH_END	0x10	/* Match at end of word */
236236769Sobrien#define VAR_NOSUBST	0x20	/* don't expand vars in VarGetPattern */
237236769Sobrien
238236769Sobrien/* Var_Set flags */
239236769Sobrien#define VAR_NO_EXPORT	0x01	/* do not export */
240236769Sobrien
241236769Sobrientypedef struct {
242236769Sobrien    /*
243236769Sobrien     * The following fields are set by Var_Parse() when it
244236769Sobrien     * encounters modifiers that need to keep state for use by
245236769Sobrien     * subsequent modifiers within the same variable expansion.
246236769Sobrien     */
247236769Sobrien    Byte	varSpace;	/* Word separator in expansions */
248236769Sobrien    Boolean	oneBigWord;	/* TRUE if we will treat the variable as a
249236769Sobrien				 * single big word, even if it contains
250236769Sobrien				 * embedded spaces (as opposed to the
251236769Sobrien				 * usual behaviour of treating it as
252236769Sobrien				 * several space-separated words). */
253236769Sobrien} Var_Parse_State;
254236769Sobrien
255236769Sobrien/* struct passed as 'void *' to VarSubstitute() for ":S/lhs/rhs/",
256236769Sobrien * to VarSYSVMatch() for ":lhs=rhs". */
257236769Sobrientypedef struct {
258236769Sobrien    const char   *lhs;	    /* String to match */
259236769Sobrien    int		  leftLen; /* Length of string */
260236769Sobrien    const char   *rhs;	    /* Replacement string (w/ &'s removed) */
261236769Sobrien    int		  rightLen; /* Length of replacement */
262236769Sobrien    int		  flags;
263236769Sobrien} VarPattern;
264236769Sobrien
265236769Sobrien/* struct passed as 'void *' to VarLoopExpand() for ":@tvar@str@" */
266236769Sobrientypedef struct {
267236769Sobrien    GNode	*ctxt;		/* variable context */
268236769Sobrien    char	*tvar;		/* name of temp var */
269236769Sobrien    int		tvarLen;
270236769Sobrien    char	*str;		/* string to expand */
271236769Sobrien    int		strLen;
272236769Sobrien    int		errnum;		/* errnum for not defined */
273236769Sobrien} VarLoop_t;
274236769Sobrien
275236769Sobrien#ifndef NO_REGEX
276236769Sobrien/* struct passed as 'void *' to VarRESubstitute() for ":C///" */
277236769Sobrientypedef struct {
278236769Sobrien    regex_t	   re;
279236769Sobrien    int		   nsub;
280236769Sobrien    regmatch_t 	  *matches;
281236769Sobrien    char 	  *replace;
282236769Sobrien    int		   flags;
283236769Sobrien} VarREPattern;
284236769Sobrien#endif
285236769Sobrien
286236769Sobrien/* struct passed to VarSelectWords() for ":[start..end]" */
287236769Sobrientypedef struct {
288236769Sobrien    int		start;		/* first word to select */
289236769Sobrien    int		end;		/* last word to select */
290236769Sobrien} VarSelectWords_t;
291236769Sobrien
292236769Sobrienstatic Var *VarFind(const char *, GNode *, int);
293236769Sobrienstatic void VarAdd(const char *, const char *, GNode *);
294236769Sobrienstatic Boolean VarHead(GNode *, Var_Parse_State *,
295236769Sobrien			char *, Boolean, Buffer *, void *);
296236769Sobrienstatic Boolean VarTail(GNode *, Var_Parse_State *,
297236769Sobrien			char *, Boolean, Buffer *, void *);
298236769Sobrienstatic Boolean VarSuffix(GNode *, Var_Parse_State *,
299236769Sobrien			char *, Boolean, Buffer *, void *);
300236769Sobrienstatic Boolean VarRoot(GNode *, Var_Parse_State *,
301236769Sobrien			char *, Boolean, Buffer *, void *);
302236769Sobrienstatic Boolean VarMatch(GNode *, Var_Parse_State *,
303236769Sobrien			char *, Boolean, Buffer *, void *);
304236769Sobrien#ifdef SYSVVARSUB
305236769Sobrienstatic Boolean VarSYSVMatch(GNode *, Var_Parse_State *,
306236769Sobrien			char *, Boolean, Buffer *, void *);
307236769Sobrien#endif
308236769Sobrienstatic Boolean VarNoMatch(GNode *, Var_Parse_State *,
309236769Sobrien			char *, Boolean, Buffer *, void *);
310236769Sobrien#ifndef NO_REGEX
311236769Sobrienstatic void VarREError(int, regex_t *, const char *);
312236769Sobrienstatic Boolean VarRESubstitute(GNode *, Var_Parse_State *,
313236769Sobrien			char *, Boolean, Buffer *, void *);
314236769Sobrien#endif
315236769Sobrienstatic Boolean VarSubstitute(GNode *, Var_Parse_State *,
316236769Sobrien			char *, Boolean, Buffer *, void *);
317236769Sobrienstatic Boolean VarLoopExpand(GNode *, Var_Parse_State *,
318236769Sobrien			char *, Boolean, Buffer *, void *);
319236769Sobrienstatic char *VarGetPattern(GNode *, Var_Parse_State *,
320236769Sobrien			   int, const char **, int, int *, int *,
321236769Sobrien			   VarPattern *);
322236769Sobrienstatic char *VarQuote(char *);
323236769Sobrienstatic char *VarHash(char *);
324236769Sobrienstatic char *VarModify(GNode *, Var_Parse_State *,
325236769Sobrien    const char *,
326236769Sobrien    Boolean (*)(GNode *, Var_Parse_State *, char *, Boolean, Buffer *, void *),
327236769Sobrien    void *);
328236769Sobrienstatic char *VarOrder(const char *, const char);
329236769Sobrienstatic char *VarUniq(const char *);
330236769Sobrienstatic int VarWordCompare(const void *, const void *);
331236769Sobrienstatic void VarPrintVar(void *);
332236769Sobrien
333236769Sobrien#define BROPEN	'{'
334236769Sobrien#define BRCLOSE	'}'
335236769Sobrien#define PROPEN	'('
336236769Sobrien#define PRCLOSE	')'
337236769Sobrien
338236769Sobrien/*-
339236769Sobrien *-----------------------------------------------------------------------
340236769Sobrien * VarFind --
341236769Sobrien *	Find the given variable in the given context and any other contexts
342236769Sobrien *	indicated.
343236769Sobrien *
344236769Sobrien * Input:
345236769Sobrien *	name		name to find
346236769Sobrien *	ctxt		context in which to find it
347236769Sobrien *	flags		FIND_GLOBAL set means to look in the
348236769Sobrien *			VAR_GLOBAL context as well. FIND_CMD set means
349236769Sobrien *			to look in the VAR_CMD context also. FIND_ENV
350236769Sobrien *			set means to look in the environment
351236769Sobrien *
352236769Sobrien * Results:
353236769Sobrien *	A pointer to the structure describing the desired variable or
354236769Sobrien *	NULL if the variable does not exist.
355236769Sobrien *
356236769Sobrien * Side Effects:
357236769Sobrien *	None
358236769Sobrien *-----------------------------------------------------------------------
359236769Sobrien */
360236769Sobrienstatic Var *
361236769SobrienVarFind(const char *name, GNode *ctxt, int flags)
362236769Sobrien{
363236769Sobrien    Hash_Entry         	*var;
364236769Sobrien    Var			*v;
365236769Sobrien
366236769Sobrien	/*
367236769Sobrien	 * If the variable name begins with a '.', it could very well be one of
368236769Sobrien	 * the local ones.  We check the name against all the local variables
369236769Sobrien	 * and substitute the short version in for 'name' if it matches one of
370236769Sobrien	 * them.
371236769Sobrien	 */
372236769Sobrien	if (*name == '.' && isupper((unsigned char) name[1]))
373236769Sobrien		switch (name[1]) {
374236769Sobrien		case 'A':
375236769Sobrien			if (!strcmp(name, ".ALLSRC"))
376236769Sobrien				name = ALLSRC;
377236769Sobrien			if (!strcmp(name, ".ARCHIVE"))
378236769Sobrien				name = ARCHIVE;
379236769Sobrien			break;
380236769Sobrien		case 'I':
381236769Sobrien			if (!strcmp(name, ".IMPSRC"))
382236769Sobrien				name = IMPSRC;
383236769Sobrien			break;
384236769Sobrien		case 'M':
385236769Sobrien			if (!strcmp(name, ".MEMBER"))
386236769Sobrien				name = MEMBER;
387236769Sobrien			break;
388236769Sobrien		case 'O':
389236769Sobrien			if (!strcmp(name, ".OODATE"))
390236769Sobrien				name = OODATE;
391236769Sobrien			break;
392236769Sobrien		case 'P':
393236769Sobrien			if (!strcmp(name, ".PREFIX"))
394236769Sobrien				name = PREFIX;
395236769Sobrien			break;
396236769Sobrien		case 'T':
397236769Sobrien			if (!strcmp(name, ".TARGET"))
398236769Sobrien				name = TARGET;
399236769Sobrien			break;
400236769Sobrien		}
401236769Sobrien#ifdef notyet
402236769Sobrien    /* for compatibility with gmake */
403236769Sobrien    if (name[0] == '^' && name[1] == '\0')
404236769Sobrien	    name = ALLSRC;
405236769Sobrien#endif
406236769Sobrien
407236769Sobrien    /*
408236769Sobrien     * First look for the variable in the given context. If it's not there,
409236769Sobrien     * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
410236769Sobrien     * depending on the FIND_* flags in 'flags'
411236769Sobrien     */
412236769Sobrien    var = Hash_FindEntry(&ctxt->context, name);
413236769Sobrien
414236769Sobrien    if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
415236769Sobrien	var = Hash_FindEntry(&VAR_CMD->context, name);
416236769Sobrien    }
417236769Sobrien    if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
418236769Sobrien	(ctxt != VAR_GLOBAL))
419236769Sobrien    {
420236769Sobrien	var = Hash_FindEntry(&VAR_GLOBAL->context, name);
421236769Sobrien    }
422236769Sobrien    if ((var == NULL) && (flags & FIND_ENV)) {
423236769Sobrien	char *env;
424236769Sobrien
425236769Sobrien	if ((env = getenv(name)) != NULL) {
426236769Sobrien	    int		len;
427236769Sobrien
428236769Sobrien	    v = bmake_malloc(sizeof(Var));
429236769Sobrien	    v->name = bmake_strdup(name);
430236769Sobrien
431236769Sobrien	    len = strlen(env);
432236769Sobrien
433236769Sobrien	    Buf_Init(&v->val, len + 1);
434236769Sobrien	    Buf_AddBytes(&v->val, len, env);
435236769Sobrien
436236769Sobrien	    v->flags = VAR_FROM_ENV;
437236769Sobrien	    return (v);
438236769Sobrien	} else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
439236769Sobrien		   (ctxt != VAR_GLOBAL))
440236769Sobrien	{
441236769Sobrien	    var = Hash_FindEntry(&VAR_GLOBAL->context, name);
442236769Sobrien	    if (var == NULL) {
443236769Sobrien		return NULL;
444236769Sobrien	    } else {
445236769Sobrien		return ((Var *)Hash_GetValue(var));
446236769Sobrien	    }
447236769Sobrien	} else {
448236769Sobrien	    return NULL;
449236769Sobrien	}
450236769Sobrien    } else if (var == NULL) {
451236769Sobrien	return NULL;
452236769Sobrien    } else {
453236769Sobrien	return ((Var *)Hash_GetValue(var));
454236769Sobrien    }
455236769Sobrien}
456236769Sobrien
457236769Sobrien/*-
458236769Sobrien *-----------------------------------------------------------------------
459236769Sobrien * VarFreeEnv  --
460236769Sobrien *	If the variable is an environment variable, free it
461236769Sobrien *
462236769Sobrien * Input:
463236769Sobrien *	v		the variable
464236769Sobrien *	destroy		true if the value buffer should be destroyed.
465236769Sobrien *
466236769Sobrien * Results:
467236769Sobrien *	1 if it is an environment variable 0 ow.
468236769Sobrien *
469236769Sobrien * Side Effects:
470236769Sobrien *	The variable is free'ed if it is an environent variable.
471236769Sobrien *-----------------------------------------------------------------------
472236769Sobrien */
473236769Sobrienstatic Boolean
474236769SobrienVarFreeEnv(Var *v, Boolean destroy)
475236769Sobrien{
476236769Sobrien    if ((v->flags & VAR_FROM_ENV) == 0)
477236769Sobrien	return FALSE;
478236769Sobrien    free(v->name);
479236769Sobrien    Buf_Destroy(&v->val, destroy);
480236769Sobrien    free(v);
481236769Sobrien    return TRUE;
482236769Sobrien}
483236769Sobrien
484236769Sobrien/*-
485236769Sobrien *-----------------------------------------------------------------------
486236769Sobrien * VarAdd  --
487236769Sobrien *	Add a new variable of name name and value val to the given context
488236769Sobrien *
489236769Sobrien * Input:
490236769Sobrien *	name		name of variable to add
491236769Sobrien *	val		value to set it to
492236769Sobrien *	ctxt		context in which to set it
493236769Sobrien *
494236769Sobrien * Results:
495236769Sobrien *	None
496236769Sobrien *
497236769Sobrien * Side Effects:
498236769Sobrien *	The new variable is placed at the front of the given context
499236769Sobrien *	The name and val arguments are duplicated so they may
500236769Sobrien *	safely be freed.
501236769Sobrien *-----------------------------------------------------------------------
502236769Sobrien */
503236769Sobrienstatic void
504236769SobrienVarAdd(const char *name, const char *val, GNode *ctxt)
505236769Sobrien{
506236769Sobrien    Var   	  *v;
507236769Sobrien    int		  len;
508236769Sobrien    Hash_Entry    *h;
509236769Sobrien
510236769Sobrien    v = bmake_malloc(sizeof(Var));
511236769Sobrien
512236769Sobrien    len = val ? strlen(val) : 0;
513236769Sobrien    Buf_Init(&v->val, len+1);
514236769Sobrien    Buf_AddBytes(&v->val, len, val);
515236769Sobrien
516236769Sobrien    v->flags = 0;
517236769Sobrien
518236769Sobrien    h = Hash_CreateEntry(&ctxt->context, name, NULL);
519236769Sobrien    Hash_SetValue(h, v);
520236769Sobrien    v->name = h->name;
521236769Sobrien    if (DEBUG(VAR)) {
522236769Sobrien	fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
523236769Sobrien    }
524236769Sobrien}
525236769Sobrien
526236769Sobrien/*-
527236769Sobrien *-----------------------------------------------------------------------
528236769Sobrien * Var_Delete --
529236769Sobrien *	Remove a variable from a context.
530236769Sobrien *
531236769Sobrien * Results:
532236769Sobrien *	None.
533236769Sobrien *
534236769Sobrien * Side Effects:
535236769Sobrien *	The Var structure is removed and freed.
536236769Sobrien *
537236769Sobrien *-----------------------------------------------------------------------
538236769Sobrien */
539236769Sobrienvoid
540236769SobrienVar_Delete(const char *name, GNode *ctxt)
541236769Sobrien{
542236769Sobrien    Hash_Entry 	  *ln;
543236769Sobrien
544236769Sobrien    ln = Hash_FindEntry(&ctxt->context, name);
545236769Sobrien    if (DEBUG(VAR)) {
546236769Sobrien	fprintf(debug_file, "%s:delete %s%s\n",
547236769Sobrien	    ctxt->name, name, ln ? "" : " (not found)");
548236769Sobrien    }
549236769Sobrien    if (ln != NULL) {
550236769Sobrien	Var 	  *v;
551236769Sobrien
552236769Sobrien	v = (Var *)Hash_GetValue(ln);
553236769Sobrien	if ((v->flags & VAR_EXPORTED)) {
554236769Sobrien	    unsetenv(v->name);
555236769Sobrien	}
556236769Sobrien	if (strcmp(MAKE_EXPORTED, v->name) == 0) {
557236769Sobrien	    var_exportedVars = VAR_EXPORTED_NONE;
558236769Sobrien	}
559236769Sobrien	if (v->name != ln->name)
560236769Sobrien		free(v->name);
561236769Sobrien	Hash_DeleteEntry(&ctxt->context, ln);
562236769Sobrien	Buf_Destroy(&v->val, TRUE);
563236769Sobrien	free(v);
564236769Sobrien    }
565236769Sobrien}
566236769Sobrien
567236769Sobrien
568236769Sobrien/*
569236769Sobrien * Export a var.
570236769Sobrien * We ignore make internal variables (those which start with '.')
571236769Sobrien * Also we jump through some hoops to avoid calling setenv
572236769Sobrien * more than necessary since it can leak.
573236769Sobrien * We only manipulate flags of vars if 'parent' is set.
574236769Sobrien */
575236769Sobrienstatic int
576236769SobrienVar_Export1(const char *name, int parent)
577236769Sobrien{
578236769Sobrien    char tmp[BUFSIZ];
579236769Sobrien    Var *v;
580236769Sobrien    char *val = NULL;
581236769Sobrien    int n;
582236769Sobrien
583236769Sobrien    if (*name == '.')
584236769Sobrien	return 0;			/* skip internals */
585236769Sobrien    if (!name[1]) {
586236769Sobrien	/*
587236769Sobrien	 * A single char.
588236769Sobrien	 * If it is one of the vars that should only appear in
589236769Sobrien	 * local context, skip it, else we can get Var_Subst
590236769Sobrien	 * into a loop.
591236769Sobrien	 */
592236769Sobrien	switch (name[0]) {
593236769Sobrien	case '@':
594236769Sobrien	case '%':
595236769Sobrien	case '*':
596236769Sobrien	case '!':
597236769Sobrien	    return 0;
598236769Sobrien	}
599236769Sobrien    }
600236769Sobrien    v = VarFind(name, VAR_GLOBAL, 0);
601236769Sobrien    if (v == NULL) {
602236769Sobrien	return 0;
603236769Sobrien    }
604236769Sobrien    if (!parent &&
605236769Sobrien	(v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
606236769Sobrien	return 0;			/* nothing to do */
607236769Sobrien    }
608236769Sobrien    val = Buf_GetAll(&v->val, NULL);
609236769Sobrien    if (strchr(val, '$')) {
610236769Sobrien	if (parent) {
611236769Sobrien	    /*
612236769Sobrien	     * Flag this as something we need to re-export.
613236769Sobrien	     * No point actually exporting it now though,
614236769Sobrien	     * the child can do it at the last minute.
615236769Sobrien	     */
616236769Sobrien	    v->flags |= (VAR_EXPORTED|VAR_REEXPORT);
617236769Sobrien	    return 1;
618236769Sobrien	}
619236769Sobrien	if (v->flags & VAR_IN_USE) {
620236769Sobrien	    /*
621236769Sobrien	     * We recursed while exporting in a child.
622236769Sobrien	     * This isn't going to end well, just skip it.
623236769Sobrien	     */
624236769Sobrien	    return 0;
625236769Sobrien	}
626236769Sobrien	n = snprintf(tmp, sizeof(tmp), "${%s}", name);
627236769Sobrien	if (n < (int)sizeof(tmp)) {
628236769Sobrien	    val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
629236769Sobrien	    setenv(name, val, 1);
630236769Sobrien	    free(val);
631236769Sobrien	}
632236769Sobrien    } else {
633236769Sobrien	if (parent) {
634236769Sobrien	    v->flags &= ~VAR_REEXPORT;	/* once will do */
635236769Sobrien	}
636236769Sobrien	if (parent || !(v->flags & VAR_EXPORTED)) {
637236769Sobrien	    setenv(name, val, 1);
638236769Sobrien	}
639236769Sobrien    }
640236769Sobrien    /*
641236769Sobrien     * This is so Var_Set knows to call Var_Export again...
642236769Sobrien     */
643236769Sobrien    if (parent) {
644236769Sobrien	v->flags |= VAR_EXPORTED;
645236769Sobrien    }
646236769Sobrien    return 1;
647236769Sobrien}
648236769Sobrien
649236769Sobrien/*
650236769Sobrien * This gets called from our children.
651236769Sobrien */
652236769Sobrienvoid
653236769SobrienVar_ExportVars(void)
654236769Sobrien{
655236769Sobrien    char tmp[BUFSIZ];
656236769Sobrien    Hash_Entry         	*var;
657236769Sobrien    Hash_Search 	state;
658236769Sobrien    Var *v;
659236769Sobrien    char *val;
660236769Sobrien    int n;
661236769Sobrien
662236769Sobrien    if (VAR_EXPORTED_NONE == var_exportedVars)
663236769Sobrien	return;
664236769Sobrien
665236769Sobrien    if (VAR_EXPORTED_ALL == var_exportedVars) {
666236769Sobrien	/*
667236769Sobrien	 * Ouch! This is crazy...
668236769Sobrien	 */
669236769Sobrien	for (var = Hash_EnumFirst(&VAR_GLOBAL->context, &state);
670236769Sobrien	     var != NULL;
671236769Sobrien	     var = Hash_EnumNext(&state)) {
672236769Sobrien	    v = (Var *)Hash_GetValue(var);
673236769Sobrien	    Var_Export1(v->name, 0);
674236769Sobrien	}
675236769Sobrien	return;
676236769Sobrien    }
677236769Sobrien    /*
678236769Sobrien     * We have a number of exported vars,
679236769Sobrien     */
680236769Sobrien    n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
681236769Sobrien    if (n < (int)sizeof(tmp)) {
682236769Sobrien	char **av;
683236769Sobrien	char *as;
684236769Sobrien	int ac;
685236769Sobrien	int i;
686236769Sobrien
687236769Sobrien	val = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
688236769Sobrien	av = brk_string(val, &ac, FALSE, &as);
689236769Sobrien	for (i = 0; i < ac; i++) {
690236769Sobrien	    Var_Export1(av[i], 0);
691236769Sobrien	}
692236769Sobrien	free(val);
693236769Sobrien	free(as);
694236769Sobrien	free(av);
695236769Sobrien    }
696236769Sobrien}
697236769Sobrien
698236769Sobrien/*
699236769Sobrien * This is called when .export is seen or
700236769Sobrien * .MAKE.EXPORTED is modified.
701236769Sobrien * It is also called when any exported var is modified.
702236769Sobrien */
703236769Sobrienvoid
704236769SobrienVar_Export(char *str, int isExport)
705236769Sobrien{
706236769Sobrien    char *name;
707236769Sobrien    char *val;
708236769Sobrien    char **av;
709236769Sobrien    char *as;
710236769Sobrien    int track;
711236769Sobrien    int ac;
712236769Sobrien    int i;
713236769Sobrien
714236769Sobrien    if (isExport && (!str || !str[0])) {
715236769Sobrien	var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
716236769Sobrien	return;
717236769Sobrien    }
718236769Sobrien
719236769Sobrien    if (strncmp(str, "-env", 4) == 0) {
720236769Sobrien	track = 0;
721236769Sobrien	str += 4;
722236769Sobrien    } else {
723236769Sobrien	track = VAR_EXPORT_PARENT;
724236769Sobrien    }
725236769Sobrien    val = Var_Subst(NULL, str, VAR_GLOBAL, 0);
726236769Sobrien    av = brk_string(val, &ac, FALSE, &as);
727236769Sobrien    for (i = 0; i < ac; i++) {
728236769Sobrien	name = av[i];
729236769Sobrien	if (!name[1]) {
730236769Sobrien	    /*
731236769Sobrien	     * A single char.
732236769Sobrien	     * If it is one of the vars that should only appear in
733236769Sobrien	     * local context, skip it, else we can get Var_Subst
734236769Sobrien	     * into a loop.
735236769Sobrien	     */
736236769Sobrien	    switch (name[0]) {
737236769Sobrien	    case '@':
738236769Sobrien	    case '%':
739236769Sobrien	    case '*':
740236769Sobrien	    case '!':
741236769Sobrien		continue;
742236769Sobrien	    }
743236769Sobrien	}
744236769Sobrien	if (Var_Export1(name, track)) {
745236769Sobrien	    if (VAR_EXPORTED_ALL != var_exportedVars)
746236769Sobrien		var_exportedVars = VAR_EXPORTED_YES;
747236769Sobrien	    if (isExport && track) {
748236769Sobrien		Var_Append(MAKE_EXPORTED, name, VAR_GLOBAL);
749236769Sobrien	    }
750236769Sobrien	}
751236769Sobrien    }
752236769Sobrien    free(val);
753236769Sobrien    free(as);
754236769Sobrien    free(av);
755236769Sobrien}
756236769Sobrien
757236769Sobrien
758236769Sobrien/*
759236769Sobrien * This is called when .unexport[-env] is seen.
760236769Sobrien */
761236769Sobrienextern char **environ;
762236769Sobrien
763236769Sobrienvoid
764236769SobrienVar_UnExport(char *str)
765236769Sobrien{
766236769Sobrien    char tmp[BUFSIZ];
767236769Sobrien    char *vlist;
768236769Sobrien    char *cp;
769236769Sobrien    Boolean unexport_env;
770236769Sobrien    int n;
771236769Sobrien
772236769Sobrien    if (!str || !str[0]) {
773236769Sobrien	return; 			/* assert? */
774236769Sobrien    }
775236769Sobrien
776236769Sobrien    vlist = NULL;
777236769Sobrien
778236769Sobrien    str += 8;
779236769Sobrien    unexport_env = (strncmp(str, "-env", 4) == 0);
780236769Sobrien    if (unexport_env) {
781236769Sobrien	char **newenv;
782236769Sobrien
783236769Sobrien	cp = getenv(MAKE_LEVEL);	/* we should preserve this */
784236769Sobrien	if (environ == savedEnv) {
785236769Sobrien	    /* we have been here before! */
786236769Sobrien	    newenv = bmake_realloc(environ, 2 * sizeof(char *));
787236769Sobrien	} else {
788236769Sobrien	    if (savedEnv) {
789236769Sobrien		free(savedEnv);
790236769Sobrien		savedEnv = NULL;
791236769Sobrien	    }
792236769Sobrien	    newenv = bmake_malloc(2 * sizeof(char *));
793236769Sobrien	}
794236769Sobrien	if (!newenv)
795236769Sobrien	    return;
796236769Sobrien	/* Note: we cannot safely free() the original environ. */
797236769Sobrien	environ = savedEnv = newenv;
798236769Sobrien	newenv[0] = NULL;
799236769Sobrien	newenv[1] = NULL;
800236769Sobrien	setenv(MAKE_LEVEL, cp, 1);
801236769Sobrien#ifdef MAKE_LEVEL_SAFE
802236769Sobrien	setenv(MAKE_LEVEL_SAFE, cp, 1);
803236769Sobrien#endif
804236769Sobrien    } else {
805236769Sobrien	for (; *str != '\n' && isspace((unsigned char) *str); str++)
806236769Sobrien	    continue;
807236769Sobrien	if (str[0] && str[0] != '\n') {
808236769Sobrien	    vlist = str;
809236769Sobrien	}
810236769Sobrien    }
811236769Sobrien
812236769Sobrien    if (!vlist) {
813236769Sobrien	/* Using .MAKE.EXPORTED */
814236769Sobrien	n = snprintf(tmp, sizeof(tmp), "${" MAKE_EXPORTED ":O:u}");
815236769Sobrien	if (n < (int)sizeof(tmp)) {
816236769Sobrien	    vlist = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
817236769Sobrien	}
818236769Sobrien    }
819236769Sobrien    if (vlist) {
820236769Sobrien	Var *v;
821236769Sobrien	char **av;
822236769Sobrien	char *as;
823236769Sobrien	int ac;
824236769Sobrien	int i;
825236769Sobrien
826236769Sobrien	av = brk_string(vlist, &ac, FALSE, &as);
827236769Sobrien	for (i = 0; i < ac; i++) {
828236769Sobrien	    v = VarFind(av[i], VAR_GLOBAL, 0);
829236769Sobrien	    if (!v)
830236769Sobrien		continue;
831236769Sobrien	    if (!unexport_env &&
832236769Sobrien		(v->flags & (VAR_EXPORTED|VAR_REEXPORT)) == VAR_EXPORTED) {
833236769Sobrien		unsetenv(v->name);
834236769Sobrien	    }
835236769Sobrien	    v->flags &= ~(VAR_EXPORTED|VAR_REEXPORT);
836236769Sobrien	    /*
837236769Sobrien	     * If we are unexporting a list,
838236769Sobrien	     * remove each one from .MAKE.EXPORTED.
839236769Sobrien	     * If we are removing them all,
840236769Sobrien	     * just delete .MAKE.EXPORTED below.
841236769Sobrien	     */
842236769Sobrien	    if (vlist == str) {
843236769Sobrien		n = snprintf(tmp, sizeof(tmp),
844236769Sobrien			     "${" MAKE_EXPORTED ":N%s}", v->name);
845236769Sobrien		if (n < (int)sizeof(tmp)) {
846236769Sobrien		    cp = Var_Subst(NULL, tmp, VAR_GLOBAL, 0);
847236769Sobrien		    Var_Set(MAKE_EXPORTED, cp, VAR_GLOBAL, 0);
848236769Sobrien		    free(cp);
849236769Sobrien		}
850236769Sobrien	    }
851236769Sobrien	}
852236769Sobrien	free(as);
853236769Sobrien	free(av);
854236769Sobrien	if (vlist != str) {
855236769Sobrien	    Var_Delete(MAKE_EXPORTED, VAR_GLOBAL);
856236769Sobrien	    free(vlist);
857236769Sobrien	}
858236769Sobrien    }
859236769Sobrien}
860236769Sobrien
861236769Sobrien/*-
862236769Sobrien *-----------------------------------------------------------------------
863236769Sobrien * Var_Set --
864236769Sobrien *	Set the variable name to the value val in the given context.
865236769Sobrien *
866236769Sobrien * Input:
867236769Sobrien *	name		name of variable to set
868236769Sobrien *	val		value to give to the variable
869236769Sobrien *	ctxt		context in which to set it
870236769Sobrien *
871236769Sobrien * Results:
872236769Sobrien *	None.
873236769Sobrien *
874236769Sobrien * Side Effects:
875236769Sobrien *	If the variable doesn't yet exist, a new record is created for it.
876236769Sobrien *	Else the old value is freed and the new one stuck in its place
877236769Sobrien *
878236769Sobrien * Notes:
879236769Sobrien *	The variable is searched for only in its context before being
880236769Sobrien *	created in that context. I.e. if the context is VAR_GLOBAL,
881236769Sobrien *	only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
882236769Sobrien *	VAR_CMD->context is searched. This is done to avoid the literally
883236769Sobrien *	thousands of unnecessary strcmp's that used to be done to
884236769Sobrien *	set, say, $(@) or $(<).
885236769Sobrien *	If the context is VAR_GLOBAL though, we check if the variable
886236769Sobrien *	was set in VAR_CMD from the command line and skip it if so.
887236769Sobrien *-----------------------------------------------------------------------
888236769Sobrien */
889236769Sobrienvoid
890236769SobrienVar_Set(const char *name, const char *val, GNode *ctxt, int flags)
891236769Sobrien{
892236769Sobrien    Var   *v;
893236769Sobrien    char *expanded_name = NULL;
894236769Sobrien
895236769Sobrien    /*
896236769Sobrien     * We only look for a variable in the given context since anything set
897236769Sobrien     * here will override anything in a lower context, so there's not much
898236769Sobrien     * point in searching them all just to save a bit of memory...
899236769Sobrien     */
900236769Sobrien    if (strchr(name, '$') != NULL) {
901236769Sobrien	expanded_name = Var_Subst(NULL, name, ctxt, 0);
902236769Sobrien	if (expanded_name[0] == 0) {
903236769Sobrien	    if (DEBUG(VAR)) {
904236769Sobrien		fprintf(debug_file, "Var_Set(\"%s\", \"%s\", ...) "
905236769Sobrien			"name expands to empty string - ignored\n",
906236769Sobrien			name, val);
907236769Sobrien	    }
908236769Sobrien	    free(expanded_name);
909236769Sobrien	    return;
910236769Sobrien	}
911236769Sobrien	name = expanded_name;
912236769Sobrien    }
913236769Sobrien    if (ctxt == VAR_GLOBAL) {
914236769Sobrien	v = VarFind(name, VAR_CMD, 0);
915236769Sobrien	if (v != NULL) {
916236769Sobrien	    if ((v->flags & VAR_FROM_CMD)) {
917236769Sobrien		if (DEBUG(VAR)) {
918236769Sobrien		    fprintf(debug_file, "%s:%s = %s ignored!\n", ctxt->name, name, val);
919236769Sobrien		}
920236769Sobrien		goto out;
921236769Sobrien	    }
922236769Sobrien	    VarFreeEnv(v, TRUE);
923236769Sobrien	}
924236769Sobrien    }
925236769Sobrien    v = VarFind(name, ctxt, 0);
926236769Sobrien    if (v == NULL) {
927236769Sobrien	VarAdd(name, val, ctxt);
928236769Sobrien    } else {
929236769Sobrien	Buf_Empty(&v->val);
930236769Sobrien	Buf_AddBytes(&v->val, strlen(val), val);
931236769Sobrien
932236769Sobrien	if (DEBUG(VAR)) {
933236769Sobrien	    fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name, val);
934236769Sobrien	}
935236769Sobrien	if ((v->flags & VAR_EXPORTED)) {
936236769Sobrien	    Var_Export1(name, VAR_EXPORT_PARENT);
937236769Sobrien	}
938236769Sobrien    }
939236769Sobrien    /*
940236769Sobrien     * Any variables given on the command line are automatically exported
941236769Sobrien     * to the environment (as per POSIX standard)
942236769Sobrien     */
943236769Sobrien    if (ctxt == VAR_CMD && (flags & VAR_NO_EXPORT) == 0) {
944236769Sobrien	if (v == NULL) {
945236769Sobrien	    /* we just added it */
946236769Sobrien	    v = VarFind(name, ctxt, 0);
947236769Sobrien	}
948236769Sobrien	if (v != NULL)
949236769Sobrien	    v->flags |= VAR_FROM_CMD;
950236769Sobrien	/*
951236769Sobrien	 * If requested, don't export these in the environment
952236769Sobrien	 * individually.  We still put them in MAKEOVERRIDES so
953236769Sobrien	 * that the command-line settings continue to override
954236769Sobrien	 * Makefile settings.
955236769Sobrien	 */
956236769Sobrien	if (varNoExportEnv != TRUE)
957236769Sobrien	    setenv(name, val, 1);
958236769Sobrien
959236769Sobrien	Var_Append(MAKEOVERRIDES, name, VAR_GLOBAL);
960236769Sobrien    }
961236769Sobrien    /*
962236769Sobrien     * Another special case.
963236769Sobrien     * Several make's support this sort of mechanism for tracking
964236769Sobrien     * recursion - but each uses a different name.
965236769Sobrien     * We allow the makefiles to update .MAKE.LEVEL and ensure
966236769Sobrien     * children see a correctly incremented value.
967236769Sobrien     */
968236769Sobrien    if (ctxt == VAR_GLOBAL && strcmp(MAKE_LEVEL, name) == 0) {
969236769Sobrien	char tmp[64];
970236769Sobrien	int level;
971236769Sobrien
972236769Sobrien	level = atoi(val);
973236769Sobrien	snprintf(tmp, sizeof(tmp), "%u", level + 1);
974236769Sobrien	setenv(MAKE_LEVEL, tmp, 1);
975236769Sobrien#ifdef MAKE_LEVEL_SAFE
976236769Sobrien	setenv(MAKE_LEVEL_SAFE, tmp, 1);
977236769Sobrien#endif
978236769Sobrien    }
979250164Ssjg#ifdef MAKE_FREEBSD_UL
980250164Ssjg    if (strcmp(MAKE_FREEBSD_UL, name) == 0) {
981250164Ssjg	FreeBSD_UL = getBoolean(MAKE_FREEBSD_UL, FALSE);
982250164Ssjg    }
983250164Ssjg#endif
984236769Sobrien
985236769Sobrien
986236769Sobrien out:
987236769Sobrien    if (expanded_name != NULL)
988236769Sobrien	free(expanded_name);
989236769Sobrien    if (v != NULL)
990236769Sobrien	VarFreeEnv(v, TRUE);
991236769Sobrien}
992236769Sobrien
993236769Sobrien/*-
994236769Sobrien *-----------------------------------------------------------------------
995236769Sobrien * Var_Append --
996236769Sobrien *	The variable of the given name has the given value appended to it in
997236769Sobrien *	the given context.
998236769Sobrien *
999236769Sobrien * Input:
1000236769Sobrien *	name		name of variable to modify
1001236769Sobrien *	val		String to append to it
1002236769Sobrien *	ctxt		Context in which this should occur
1003236769Sobrien *
1004236769Sobrien * Results:
1005236769Sobrien *	None
1006236769Sobrien *
1007236769Sobrien * Side Effects:
1008236769Sobrien *	If the variable doesn't exist, it is created. Else the strings
1009236769Sobrien *	are concatenated (with a space in between).
1010236769Sobrien *
1011236769Sobrien * Notes:
1012236769Sobrien *	Only if the variable is being sought in the global context is the
1013236769Sobrien *	environment searched.
1014236769Sobrien *	XXX: Knows its calling circumstances in that if called with ctxt
1015236769Sobrien *	an actual target, it will only search that context since only
1016236769Sobrien *	a local variable could be being appended to. This is actually
1017236769Sobrien *	a big win and must be tolerated.
1018236769Sobrien *-----------------------------------------------------------------------
1019236769Sobrien */
1020236769Sobrienvoid
1021236769SobrienVar_Append(const char *name, const char *val, GNode *ctxt)
1022236769Sobrien{
1023236769Sobrien    Var		   *v;
1024236769Sobrien    Hash_Entry	   *h;
1025236769Sobrien    char *expanded_name = NULL;
1026236769Sobrien
1027236769Sobrien    if (strchr(name, '$') != NULL) {
1028236769Sobrien	expanded_name = Var_Subst(NULL, name, ctxt, 0);
1029236769Sobrien	if (expanded_name[0] == 0) {
1030236769Sobrien	    if (DEBUG(VAR)) {
1031236769Sobrien		fprintf(debug_file, "Var_Append(\"%s\", \"%s\", ...) "
1032236769Sobrien			"name expands to empty string - ignored\n",
1033236769Sobrien			name, val);
1034236769Sobrien	    }
1035236769Sobrien	    free(expanded_name);
1036236769Sobrien	    return;
1037236769Sobrien	}
1038236769Sobrien	name = expanded_name;
1039236769Sobrien    }
1040236769Sobrien
1041236769Sobrien    v = VarFind(name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
1042236769Sobrien
1043236769Sobrien    if (v == NULL) {
1044236769Sobrien	VarAdd(name, val, ctxt);
1045236769Sobrien    } else {
1046236769Sobrien	Buf_AddByte(&v->val, ' ');
1047236769Sobrien	Buf_AddBytes(&v->val, strlen(val), val);
1048236769Sobrien
1049236769Sobrien	if (DEBUG(VAR)) {
1050236769Sobrien	    fprintf(debug_file, "%s:%s = %s\n", ctxt->name, name,
1051236769Sobrien		   Buf_GetAll(&v->val, NULL));
1052236769Sobrien	}
1053236769Sobrien
1054236769Sobrien	if (v->flags & VAR_FROM_ENV) {
1055236769Sobrien	    /*
1056236769Sobrien	     * If the original variable came from the environment, we
1057236769Sobrien	     * have to install it in the global context (we could place
1058236769Sobrien	     * it in the environment, but then we should provide a way to
1059236769Sobrien	     * export other variables...)
1060236769Sobrien	     */
1061236769Sobrien	    v->flags &= ~VAR_FROM_ENV;
1062236769Sobrien	    h = Hash_CreateEntry(&ctxt->context, name, NULL);
1063236769Sobrien	    Hash_SetValue(h, v);
1064236769Sobrien	}
1065236769Sobrien    }
1066236769Sobrien    if (expanded_name != NULL)
1067236769Sobrien	free(expanded_name);
1068236769Sobrien}
1069236769Sobrien
1070236769Sobrien/*-
1071236769Sobrien *-----------------------------------------------------------------------
1072236769Sobrien * Var_Exists --
1073236769Sobrien *	See if the given variable exists.
1074236769Sobrien *
1075236769Sobrien * Input:
1076236769Sobrien *	name		Variable to find
1077236769Sobrien *	ctxt		Context in which to start search
1078236769Sobrien *
1079236769Sobrien * Results:
1080236769Sobrien *	TRUE if it does, FALSE if it doesn't
1081236769Sobrien *
1082236769Sobrien * Side Effects:
1083236769Sobrien *	None.
1084236769Sobrien *
1085236769Sobrien *-----------------------------------------------------------------------
1086236769Sobrien */
1087236769SobrienBoolean
1088236769SobrienVar_Exists(const char *name, GNode *ctxt)
1089236769Sobrien{
1090236769Sobrien    Var		  *v;
1091236769Sobrien    char          *cp;
1092236769Sobrien
1093236769Sobrien    if ((cp = strchr(name, '$')) != NULL) {
1094236769Sobrien	cp = Var_Subst(NULL, name, ctxt, FALSE);
1095236769Sobrien    }
1096236769Sobrien    v = VarFind(cp ? cp : name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
1097236769Sobrien    if (cp != NULL) {
1098236769Sobrien	free(cp);
1099236769Sobrien    }
1100236769Sobrien    if (v == NULL) {
1101236769Sobrien	return(FALSE);
1102236769Sobrien    } else {
1103236769Sobrien	(void)VarFreeEnv(v, TRUE);
1104236769Sobrien    }
1105236769Sobrien    return(TRUE);
1106236769Sobrien}
1107236769Sobrien
1108236769Sobrien/*-
1109236769Sobrien *-----------------------------------------------------------------------
1110236769Sobrien * Var_Value --
1111236769Sobrien *	Return the value of the named variable in the given context
1112236769Sobrien *
1113236769Sobrien * Input:
1114236769Sobrien *	name		name to find
1115236769Sobrien *	ctxt		context in which to search for it
1116236769Sobrien *
1117236769Sobrien * Results:
1118236769Sobrien *	The value if the variable exists, NULL if it doesn't
1119236769Sobrien *
1120236769Sobrien * Side Effects:
1121236769Sobrien *	None
1122236769Sobrien *-----------------------------------------------------------------------
1123236769Sobrien */
1124236769Sobrienchar *
1125236769SobrienVar_Value(const char *name, GNode *ctxt, char **frp)
1126236769Sobrien{
1127236769Sobrien    Var            *v;
1128236769Sobrien
1129236769Sobrien    v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
1130236769Sobrien    *frp = NULL;
1131236769Sobrien    if (v != NULL) {
1132236769Sobrien	char *p = (Buf_GetAll(&v->val, NULL));
1133236769Sobrien	if (VarFreeEnv(v, FALSE))
1134236769Sobrien	    *frp = p;
1135236769Sobrien	return p;
1136236769Sobrien    } else {
1137236769Sobrien	return NULL;
1138236769Sobrien    }
1139236769Sobrien}
1140236769Sobrien
1141236769Sobrien/*-
1142236769Sobrien *-----------------------------------------------------------------------
1143236769Sobrien * VarHead --
1144236769Sobrien *	Remove the tail of the given word and place the result in the given
1145236769Sobrien *	buffer.
1146236769Sobrien *
1147236769Sobrien * Input:
1148236769Sobrien *	word		Word to trim
1149236769Sobrien *	addSpace	True if need to add a space to the buffer
1150236769Sobrien *			before sticking in the head
1151236769Sobrien *	buf		Buffer in which to store it
1152236769Sobrien *
1153236769Sobrien * Results:
1154236769Sobrien *	TRUE if characters were added to the buffer (a space needs to be
1155236769Sobrien *	added to the buffer before the next word).
1156236769Sobrien *
1157236769Sobrien * Side Effects:
1158236769Sobrien *	The trimmed word is added to the buffer.
1159236769Sobrien *
1160236769Sobrien *-----------------------------------------------------------------------
1161236769Sobrien */
1162236769Sobrienstatic Boolean
1163237578SobrienVarHead(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1164236769Sobrien	char *word, Boolean addSpace, Buffer *buf,
1165236769Sobrien	void *dummy)
1166236769Sobrien{
1167236769Sobrien    char *slash;
1168236769Sobrien
1169236769Sobrien    slash = strrchr(word, '/');
1170236769Sobrien    if (slash != NULL) {
1171236769Sobrien	if (addSpace && vpstate->varSpace) {
1172236769Sobrien	    Buf_AddByte(buf, vpstate->varSpace);
1173236769Sobrien	}
1174236769Sobrien	*slash = '\0';
1175236769Sobrien	Buf_AddBytes(buf, strlen(word), word);
1176236769Sobrien	*slash = '/';
1177236769Sobrien	return (TRUE);
1178236769Sobrien    } else {
1179236769Sobrien	/*
1180236769Sobrien	 * If no directory part, give . (q.v. the POSIX standard)
1181236769Sobrien	 */
1182236769Sobrien	if (addSpace && vpstate->varSpace)
1183236769Sobrien	    Buf_AddByte(buf, vpstate->varSpace);
1184236769Sobrien	Buf_AddByte(buf, '.');
1185236769Sobrien    }
1186236769Sobrien    return(dummy ? TRUE : TRUE);
1187236769Sobrien}
1188236769Sobrien
1189236769Sobrien/*-
1190236769Sobrien *-----------------------------------------------------------------------
1191236769Sobrien * VarTail --
1192236769Sobrien *	Remove the head of the given word and place the result in the given
1193236769Sobrien *	buffer.
1194236769Sobrien *
1195236769Sobrien * Input:
1196236769Sobrien *	word		Word to trim
1197236769Sobrien *	addSpace	True if need to add a space to the buffer
1198236769Sobrien *			before adding the tail
1199236769Sobrien *	buf		Buffer in which to store it
1200236769Sobrien *
1201236769Sobrien * Results:
1202236769Sobrien *	TRUE if characters were added to the buffer (a space needs to be
1203236769Sobrien *	added to the buffer before the next word).
1204236769Sobrien *
1205236769Sobrien * Side Effects:
1206236769Sobrien *	The trimmed word is added to the buffer.
1207236769Sobrien *
1208236769Sobrien *-----------------------------------------------------------------------
1209236769Sobrien */
1210236769Sobrienstatic Boolean
1211237578SobrienVarTail(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1212236769Sobrien	char *word, Boolean addSpace, Buffer *buf,
1213236769Sobrien	void *dummy)
1214236769Sobrien{
1215236769Sobrien    char *slash;
1216236769Sobrien
1217236769Sobrien    if (addSpace && vpstate->varSpace) {
1218236769Sobrien	Buf_AddByte(buf, vpstate->varSpace);
1219236769Sobrien    }
1220236769Sobrien
1221236769Sobrien    slash = strrchr(word, '/');
1222236769Sobrien    if (slash != NULL) {
1223236769Sobrien	*slash++ = '\0';
1224236769Sobrien	Buf_AddBytes(buf, strlen(slash), slash);
1225236769Sobrien	slash[-1] = '/';
1226236769Sobrien    } else {
1227236769Sobrien	Buf_AddBytes(buf, strlen(word), word);
1228236769Sobrien    }
1229236769Sobrien    return (dummy ? TRUE : TRUE);
1230236769Sobrien}
1231236769Sobrien
1232236769Sobrien/*-
1233236769Sobrien *-----------------------------------------------------------------------
1234236769Sobrien * VarSuffix --
1235236769Sobrien *	Place the suffix of the given word in the given buffer.
1236236769Sobrien *
1237236769Sobrien * Input:
1238236769Sobrien *	word		Word to trim
1239236769Sobrien *	addSpace	TRUE if need to add a space before placing the
1240236769Sobrien *			suffix in the buffer
1241236769Sobrien *	buf		Buffer in which to store it
1242236769Sobrien *
1243236769Sobrien * Results:
1244236769Sobrien *	TRUE if characters were added to the buffer (a space needs to be
1245236769Sobrien *	added to the buffer before the next word).
1246236769Sobrien *
1247236769Sobrien * Side Effects:
1248236769Sobrien *	The suffix from the word is placed in the buffer.
1249236769Sobrien *
1250236769Sobrien *-----------------------------------------------------------------------
1251236769Sobrien */
1252236769Sobrienstatic Boolean
1253237578SobrienVarSuffix(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1254236769Sobrien	  char *word, Boolean addSpace, Buffer *buf,
1255236769Sobrien	  void *dummy)
1256236769Sobrien{
1257236769Sobrien    char *dot;
1258236769Sobrien
1259236769Sobrien    dot = strrchr(word, '.');
1260236769Sobrien    if (dot != NULL) {
1261236769Sobrien	if (addSpace && vpstate->varSpace) {
1262236769Sobrien	    Buf_AddByte(buf, vpstate->varSpace);
1263236769Sobrien	}
1264236769Sobrien	*dot++ = '\0';
1265236769Sobrien	Buf_AddBytes(buf, strlen(dot), dot);
1266236769Sobrien	dot[-1] = '.';
1267236769Sobrien	addSpace = TRUE;
1268236769Sobrien    }
1269236769Sobrien    return (dummy ? addSpace : addSpace);
1270236769Sobrien}
1271236769Sobrien
1272236769Sobrien/*-
1273236769Sobrien *-----------------------------------------------------------------------
1274236769Sobrien * VarRoot --
1275236769Sobrien *	Remove the suffix of the given word and place the result in the
1276236769Sobrien *	buffer.
1277236769Sobrien *
1278236769Sobrien * Input:
1279236769Sobrien *	word		Word to trim
1280236769Sobrien *	addSpace	TRUE if need to add a space to the buffer
1281236769Sobrien *			before placing the root in it
1282236769Sobrien *	buf		Buffer in which to store it
1283236769Sobrien *
1284236769Sobrien * Results:
1285236769Sobrien *	TRUE if characters were added to the buffer (a space needs to be
1286236769Sobrien *	added to the buffer before the next word).
1287236769Sobrien *
1288236769Sobrien * Side Effects:
1289236769Sobrien *	The trimmed word is added to the buffer.
1290236769Sobrien *
1291236769Sobrien *-----------------------------------------------------------------------
1292236769Sobrien */
1293236769Sobrienstatic Boolean
1294237578SobrienVarRoot(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1295236769Sobrien	char *word, Boolean addSpace, Buffer *buf,
1296236769Sobrien	void *dummy)
1297236769Sobrien{
1298236769Sobrien    char *dot;
1299236769Sobrien
1300236769Sobrien    if (addSpace && vpstate->varSpace) {
1301236769Sobrien	Buf_AddByte(buf, vpstate->varSpace);
1302236769Sobrien    }
1303236769Sobrien
1304236769Sobrien    dot = strrchr(word, '.');
1305236769Sobrien    if (dot != NULL) {
1306236769Sobrien	*dot = '\0';
1307236769Sobrien	Buf_AddBytes(buf, strlen(word), word);
1308236769Sobrien	*dot = '.';
1309236769Sobrien    } else {
1310236769Sobrien	Buf_AddBytes(buf, strlen(word), word);
1311236769Sobrien    }
1312236769Sobrien    return (dummy ? TRUE : TRUE);
1313236769Sobrien}
1314236769Sobrien
1315236769Sobrien/*-
1316236769Sobrien *-----------------------------------------------------------------------
1317236769Sobrien * VarMatch --
1318236769Sobrien *	Place the word in the buffer if it matches the given pattern.
1319236769Sobrien *	Callback function for VarModify to implement the :M modifier.
1320236769Sobrien *
1321236769Sobrien * Input:
1322236769Sobrien *	word		Word to examine
1323236769Sobrien *	addSpace	TRUE if need to add a space to the buffer
1324236769Sobrien *			before adding the word, if it matches
1325236769Sobrien *	buf		Buffer in which to store it
1326236769Sobrien *	pattern		Pattern the word must match
1327236769Sobrien *
1328236769Sobrien * Results:
1329236769Sobrien *	TRUE if a space should be placed in the buffer before the next
1330236769Sobrien *	word.
1331236769Sobrien *
1332236769Sobrien * Side Effects:
1333236769Sobrien *	The word may be copied to the buffer.
1334236769Sobrien *
1335236769Sobrien *-----------------------------------------------------------------------
1336236769Sobrien */
1337236769Sobrienstatic Boolean
1338237578SobrienVarMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1339236769Sobrien	 char *word, Boolean addSpace, Buffer *buf,
1340236769Sobrien	 void *pattern)
1341236769Sobrien{
1342236769Sobrien    if (DEBUG(VAR))
1343236769Sobrien	fprintf(debug_file, "VarMatch [%s] [%s]\n", word, (char *)pattern);
1344236769Sobrien    if (Str_Match(word, (char *)pattern)) {
1345236769Sobrien	if (addSpace && vpstate->varSpace) {
1346236769Sobrien	    Buf_AddByte(buf, vpstate->varSpace);
1347236769Sobrien	}
1348236769Sobrien	addSpace = TRUE;
1349236769Sobrien	Buf_AddBytes(buf, strlen(word), word);
1350236769Sobrien    }
1351236769Sobrien    return(addSpace);
1352236769Sobrien}
1353236769Sobrien
1354236769Sobrien#ifdef SYSVVARSUB
1355236769Sobrien/*-
1356236769Sobrien *-----------------------------------------------------------------------
1357236769Sobrien * VarSYSVMatch --
1358236769Sobrien *	Place the word in the buffer if it matches the given pattern.
1359236769Sobrien *	Callback function for VarModify to implement the System V %
1360236769Sobrien *	modifiers.
1361236769Sobrien *
1362236769Sobrien * Input:
1363236769Sobrien *	word		Word to examine
1364236769Sobrien *	addSpace	TRUE if need to add a space to the buffer
1365236769Sobrien *			before adding the word, if it matches
1366236769Sobrien *	buf		Buffer in which to store it
1367236769Sobrien *	patp		Pattern the word must match
1368236769Sobrien *
1369236769Sobrien * Results:
1370236769Sobrien *	TRUE if a space should be placed in the buffer before the next
1371236769Sobrien *	word.
1372236769Sobrien *
1373236769Sobrien * Side Effects:
1374236769Sobrien *	The word may be copied to the buffer.
1375236769Sobrien *
1376236769Sobrien *-----------------------------------------------------------------------
1377236769Sobrien */
1378236769Sobrienstatic Boolean
1379236769SobrienVarSYSVMatch(GNode *ctx, Var_Parse_State *vpstate,
1380236769Sobrien	     char *word, Boolean addSpace, Buffer *buf,
1381236769Sobrien	     void *patp)
1382236769Sobrien{
1383236769Sobrien    int len;
1384236769Sobrien    char *ptr;
1385236769Sobrien    VarPattern 	  *pat = (VarPattern *)patp;
1386236769Sobrien    char *varexp;
1387236769Sobrien
1388236769Sobrien    if (addSpace && vpstate->varSpace)
1389236769Sobrien	Buf_AddByte(buf, vpstate->varSpace);
1390236769Sobrien
1391236769Sobrien    addSpace = TRUE;
1392236769Sobrien
1393236769Sobrien    if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL) {
1394236769Sobrien        varexp = Var_Subst(NULL, pat->rhs, ctx, 0);
1395236769Sobrien	Str_SYSVSubst(buf, varexp, ptr, len);
1396236769Sobrien	free(varexp);
1397236769Sobrien    } else {
1398236769Sobrien	Buf_AddBytes(buf, strlen(word), word);
1399236769Sobrien    }
1400236769Sobrien
1401236769Sobrien    return(addSpace);
1402236769Sobrien}
1403236769Sobrien#endif
1404236769Sobrien
1405236769Sobrien
1406236769Sobrien/*-
1407236769Sobrien *-----------------------------------------------------------------------
1408236769Sobrien * VarNoMatch --
1409236769Sobrien *	Place the word in the buffer if it doesn't match the given pattern.
1410236769Sobrien *	Callback function for VarModify to implement the :N modifier.
1411236769Sobrien *
1412236769Sobrien * Input:
1413236769Sobrien *	word		Word to examine
1414236769Sobrien *	addSpace	TRUE if need to add a space to the buffer
1415236769Sobrien *			before adding the word, if it matches
1416236769Sobrien *	buf		Buffer in which to store it
1417236769Sobrien *	pattern		Pattern the word must match
1418236769Sobrien *
1419236769Sobrien * Results:
1420236769Sobrien *	TRUE if a space should be placed in the buffer before the next
1421236769Sobrien *	word.
1422236769Sobrien *
1423236769Sobrien * Side Effects:
1424236769Sobrien *	The word may be copied to the buffer.
1425236769Sobrien *
1426236769Sobrien *-----------------------------------------------------------------------
1427236769Sobrien */
1428236769Sobrienstatic Boolean
1429237578SobrienVarNoMatch(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1430236769Sobrien	   char *word, Boolean addSpace, Buffer *buf,
1431236769Sobrien	   void *pattern)
1432236769Sobrien{
1433236769Sobrien    if (!Str_Match(word, (char *)pattern)) {
1434236769Sobrien	if (addSpace && vpstate->varSpace) {
1435236769Sobrien	    Buf_AddByte(buf, vpstate->varSpace);
1436236769Sobrien	}
1437236769Sobrien	addSpace = TRUE;
1438236769Sobrien	Buf_AddBytes(buf, strlen(word), word);
1439236769Sobrien    }
1440236769Sobrien    return(addSpace);
1441236769Sobrien}
1442236769Sobrien
1443236769Sobrien
1444236769Sobrien/*-
1445236769Sobrien *-----------------------------------------------------------------------
1446236769Sobrien * VarSubstitute --
1447236769Sobrien *	Perform a string-substitution on the given word, placing the
1448236769Sobrien *	result in the passed buffer.
1449236769Sobrien *
1450236769Sobrien * Input:
1451236769Sobrien *	word		Word to modify
1452236769Sobrien *	addSpace	True if space should be added before
1453236769Sobrien *			other characters
1454236769Sobrien *	buf		Buffer for result
1455236769Sobrien *	patternp	Pattern for substitution
1456236769Sobrien *
1457236769Sobrien * Results:
1458236769Sobrien *	TRUE if a space is needed before more characters are added.
1459236769Sobrien *
1460236769Sobrien * Side Effects:
1461236769Sobrien *	None.
1462236769Sobrien *
1463236769Sobrien *-----------------------------------------------------------------------
1464236769Sobrien */
1465236769Sobrienstatic Boolean
1466237578SobrienVarSubstitute(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1467236769Sobrien	      char *word, Boolean addSpace, Buffer *buf,
1468236769Sobrien	      void *patternp)
1469236769Sobrien{
1470236769Sobrien    int  	wordLen;    /* Length of word */
1471236769Sobrien    char 	*cp;	    /* General pointer */
1472236769Sobrien    VarPattern	*pattern = (VarPattern *)patternp;
1473236769Sobrien
1474236769Sobrien    wordLen = strlen(word);
1475236769Sobrien    if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
1476236769Sobrien	(VAR_SUB_ONE|VAR_SUB_MATCHED)) {
1477236769Sobrien	/*
1478236769Sobrien	 * Still substituting -- break it down into simple anchored cases
1479236769Sobrien	 * and if none of them fits, perform the general substitution case.
1480236769Sobrien	 */
1481236769Sobrien	if ((pattern->flags & VAR_MATCH_START) &&
1482236769Sobrien	    (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
1483236769Sobrien		/*
1484236769Sobrien		 * Anchored at start and beginning of word matches pattern
1485236769Sobrien		 */
1486236769Sobrien		if ((pattern->flags & VAR_MATCH_END) &&
1487236769Sobrien		    (wordLen == pattern->leftLen)) {
1488236769Sobrien			/*
1489236769Sobrien			 * Also anchored at end and matches to the end (word
1490236769Sobrien			 * is same length as pattern) add space and rhs only
1491236769Sobrien			 * if rhs is non-null.
1492236769Sobrien			 */
1493236769Sobrien			if (pattern->rightLen != 0) {
1494236769Sobrien			    if (addSpace && vpstate->varSpace) {
1495236769Sobrien				Buf_AddByte(buf, vpstate->varSpace);
1496236769Sobrien			    }
1497236769Sobrien			    addSpace = TRUE;
1498236769Sobrien			    Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1499236769Sobrien			}
1500236769Sobrien			pattern->flags |= VAR_SUB_MATCHED;
1501236769Sobrien		} else if (pattern->flags & VAR_MATCH_END) {
1502236769Sobrien		    /*
1503236769Sobrien		     * Doesn't match to end -- copy word wholesale
1504236769Sobrien		     */
1505236769Sobrien		    goto nosub;
1506236769Sobrien		} else {
1507236769Sobrien		    /*
1508236769Sobrien		     * Matches at start but need to copy in trailing characters
1509236769Sobrien		     */
1510236769Sobrien		    if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
1511236769Sobrien			if (addSpace && vpstate->varSpace) {
1512236769Sobrien			    Buf_AddByte(buf, vpstate->varSpace);
1513236769Sobrien			}
1514236769Sobrien			addSpace = TRUE;
1515236769Sobrien		    }
1516236769Sobrien		    Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1517236769Sobrien		    Buf_AddBytes(buf, wordLen - pattern->leftLen,
1518236769Sobrien				 (word + pattern->leftLen));
1519236769Sobrien		    pattern->flags |= VAR_SUB_MATCHED;
1520236769Sobrien		}
1521236769Sobrien	} else if (pattern->flags & VAR_MATCH_START) {
1522236769Sobrien	    /*
1523236769Sobrien	     * Had to match at start of word and didn't -- copy whole word.
1524236769Sobrien	     */
1525236769Sobrien	    goto nosub;
1526236769Sobrien	} else if (pattern->flags & VAR_MATCH_END) {
1527236769Sobrien	    /*
1528236769Sobrien	     * Anchored at end, Find only place match could occur (leftLen
1529236769Sobrien	     * characters from the end of the word) and see if it does. Note
1530236769Sobrien	     * that because the $ will be left at the end of the lhs, we have
1531236769Sobrien	     * to use strncmp.
1532236769Sobrien	     */
1533236769Sobrien	    cp = word + (wordLen - pattern->leftLen);
1534236769Sobrien	    if ((cp >= word) &&
1535236769Sobrien		(strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
1536236769Sobrien		/*
1537236769Sobrien		 * Match found. If we will place characters in the buffer,
1538236769Sobrien		 * add a space before hand as indicated by addSpace, then
1539236769Sobrien		 * stuff in the initial, unmatched part of the word followed
1540236769Sobrien		 * by the right-hand-side.
1541236769Sobrien		 */
1542236769Sobrien		if (((cp - word) + pattern->rightLen) != 0) {
1543236769Sobrien		    if (addSpace && vpstate->varSpace) {
1544236769Sobrien			Buf_AddByte(buf, vpstate->varSpace);
1545236769Sobrien		    }
1546236769Sobrien		    addSpace = TRUE;
1547236769Sobrien		}
1548236769Sobrien		Buf_AddBytes(buf, cp - word, word);
1549236769Sobrien		Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1550236769Sobrien		pattern->flags |= VAR_SUB_MATCHED;
1551236769Sobrien	    } else {
1552236769Sobrien		/*
1553236769Sobrien		 * Had to match at end and didn't. Copy entire word.
1554236769Sobrien		 */
1555236769Sobrien		goto nosub;
1556236769Sobrien	    }
1557236769Sobrien	} else {
1558236769Sobrien	    /*
1559236769Sobrien	     * Pattern is unanchored: search for the pattern in the word using
1560236769Sobrien	     * String_FindSubstring, copying unmatched portions and the
1561236769Sobrien	     * right-hand-side for each match found, handling non-global
1562236769Sobrien	     * substitutions correctly, etc. When the loop is done, any
1563236769Sobrien	     * remaining part of the word (word and wordLen are adjusted
1564236769Sobrien	     * accordingly through the loop) is copied straight into the
1565236769Sobrien	     * buffer.
1566236769Sobrien	     * addSpace is set FALSE as soon as a space is added to the
1567236769Sobrien	     * buffer.
1568236769Sobrien	     */
1569236769Sobrien	    Boolean done;
1570236769Sobrien	    int origSize;
1571236769Sobrien
1572236769Sobrien	    done = FALSE;
1573236769Sobrien	    origSize = Buf_Size(buf);
1574236769Sobrien	    while (!done) {
1575236769Sobrien		cp = Str_FindSubstring(word, pattern->lhs);
1576236769Sobrien		if (cp != NULL) {
1577236769Sobrien		    if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
1578236769Sobrien			Buf_AddByte(buf, vpstate->varSpace);
1579236769Sobrien			addSpace = FALSE;
1580236769Sobrien		    }
1581236769Sobrien		    Buf_AddBytes(buf, cp-word, word);
1582236769Sobrien		    Buf_AddBytes(buf, pattern->rightLen, pattern->rhs);
1583236769Sobrien		    wordLen -= (cp - word) + pattern->leftLen;
1584236769Sobrien		    word = cp + pattern->leftLen;
1585236769Sobrien		    if (wordLen == 0) {
1586236769Sobrien			done = TRUE;
1587236769Sobrien		    }
1588236769Sobrien		    if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
1589236769Sobrien			done = TRUE;
1590236769Sobrien		    }
1591236769Sobrien		    pattern->flags |= VAR_SUB_MATCHED;
1592236769Sobrien		} else {
1593236769Sobrien		    done = TRUE;
1594236769Sobrien		}
1595236769Sobrien	    }
1596236769Sobrien	    if (wordLen != 0) {
1597236769Sobrien		if (addSpace && vpstate->varSpace) {
1598236769Sobrien		    Buf_AddByte(buf, vpstate->varSpace);
1599236769Sobrien		}
1600236769Sobrien		Buf_AddBytes(buf, wordLen, word);
1601236769Sobrien	    }
1602236769Sobrien	    /*
1603236769Sobrien	     * If added characters to the buffer, need to add a space
1604236769Sobrien	     * before we add any more. If we didn't add any, just return
1605236769Sobrien	     * the previous value of addSpace.
1606236769Sobrien	     */
1607236769Sobrien	    return ((Buf_Size(buf) != origSize) || addSpace);
1608236769Sobrien	}
1609236769Sobrien	return (addSpace);
1610236769Sobrien    }
1611236769Sobrien nosub:
1612236769Sobrien    if (addSpace && vpstate->varSpace) {
1613236769Sobrien	Buf_AddByte(buf, vpstate->varSpace);
1614236769Sobrien    }
1615236769Sobrien    Buf_AddBytes(buf, wordLen, word);
1616236769Sobrien    return(TRUE);
1617236769Sobrien}
1618236769Sobrien
1619236769Sobrien#ifndef NO_REGEX
1620236769Sobrien/*-
1621236769Sobrien *-----------------------------------------------------------------------
1622236769Sobrien * VarREError --
1623236769Sobrien *	Print the error caused by a regcomp or regexec call.
1624236769Sobrien *
1625236769Sobrien * Results:
1626236769Sobrien *	None.
1627236769Sobrien *
1628236769Sobrien * Side Effects:
1629236769Sobrien *	An error gets printed.
1630236769Sobrien *
1631236769Sobrien *-----------------------------------------------------------------------
1632236769Sobrien */
1633236769Sobrienstatic void
1634236769SobrienVarREError(int errnum, regex_t *pat, const char *str)
1635236769Sobrien{
1636236769Sobrien    char *errbuf;
1637236769Sobrien    int errlen;
1638236769Sobrien
1639236769Sobrien    errlen = regerror(errnum, pat, 0, 0);
1640236769Sobrien    errbuf = bmake_malloc(errlen);
1641236769Sobrien    regerror(errnum, pat, errbuf, errlen);
1642236769Sobrien    Error("%s: %s", str, errbuf);
1643236769Sobrien    free(errbuf);
1644236769Sobrien}
1645236769Sobrien
1646236769Sobrien
1647236769Sobrien/*-
1648236769Sobrien *-----------------------------------------------------------------------
1649236769Sobrien * VarRESubstitute --
1650236769Sobrien *	Perform a regex substitution on the given word, placing the
1651236769Sobrien *	result in the passed buffer.
1652236769Sobrien *
1653236769Sobrien * Results:
1654236769Sobrien *	TRUE if a space is needed before more characters are added.
1655236769Sobrien *
1656236769Sobrien * Side Effects:
1657236769Sobrien *	None.
1658236769Sobrien *
1659236769Sobrien *-----------------------------------------------------------------------
1660236769Sobrien */
1661236769Sobrienstatic Boolean
1662237578SobrienVarRESubstitute(GNode *ctx MAKE_ATTR_UNUSED,
1663237578Sobrien		Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1664236769Sobrien		char *word, Boolean addSpace, Buffer *buf,
1665236769Sobrien		void *patternp)
1666236769Sobrien{
1667236769Sobrien    VarREPattern *pat;
1668236769Sobrien    int xrv;
1669236769Sobrien    char *wp;
1670236769Sobrien    char *rp;
1671236769Sobrien    int added;
1672236769Sobrien    int flags = 0;
1673236769Sobrien
1674236769Sobrien#define MAYBE_ADD_SPACE()		\
1675236769Sobrien	if (addSpace && !added)		\
1676236769Sobrien	    Buf_AddByte(buf, ' ');	\
1677236769Sobrien	added = 1
1678236769Sobrien
1679236769Sobrien    added = 0;
1680236769Sobrien    wp = word;
1681236769Sobrien    pat = patternp;
1682236769Sobrien
1683236769Sobrien    if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
1684236769Sobrien	(VAR_SUB_ONE|VAR_SUB_MATCHED))
1685236769Sobrien	xrv = REG_NOMATCH;
1686236769Sobrien    else {
1687236769Sobrien    tryagain:
1688236769Sobrien	xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
1689236769Sobrien    }
1690236769Sobrien
1691236769Sobrien    switch (xrv) {
1692236769Sobrien    case 0:
1693236769Sobrien	pat->flags |= VAR_SUB_MATCHED;
1694236769Sobrien	if (pat->matches[0].rm_so > 0) {
1695236769Sobrien	    MAYBE_ADD_SPACE();
1696236769Sobrien	    Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
1697236769Sobrien	}
1698236769Sobrien
1699236769Sobrien	for (rp = pat->replace; *rp; rp++) {
1700236769Sobrien	    if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
1701236769Sobrien		MAYBE_ADD_SPACE();
1702236769Sobrien		Buf_AddByte(buf,rp[1]);
1703236769Sobrien		rp++;
1704236769Sobrien	    }
1705236769Sobrien	    else if ((*rp == '&') ||
1706236769Sobrien		((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
1707236769Sobrien		int n;
1708236769Sobrien		const char *subbuf;
1709236769Sobrien		int sublen;
1710236769Sobrien		char errstr[3];
1711236769Sobrien
1712236769Sobrien		if (*rp == '&') {
1713236769Sobrien		    n = 0;
1714236769Sobrien		    errstr[0] = '&';
1715236769Sobrien		    errstr[1] = '\0';
1716236769Sobrien		} else {
1717236769Sobrien		    n = rp[1] - '0';
1718236769Sobrien		    errstr[0] = '\\';
1719236769Sobrien		    errstr[1] = rp[1];
1720236769Sobrien		    errstr[2] = '\0';
1721236769Sobrien		    rp++;
1722236769Sobrien		}
1723236769Sobrien
1724236769Sobrien		if (n > pat->nsub) {
1725236769Sobrien		    Error("No subexpression %s", &errstr[0]);
1726236769Sobrien		    subbuf = "";
1727236769Sobrien		    sublen = 0;
1728236769Sobrien		} else if ((pat->matches[n].rm_so == -1) &&
1729236769Sobrien			   (pat->matches[n].rm_eo == -1)) {
1730236769Sobrien		    Error("No match for subexpression %s", &errstr[0]);
1731236769Sobrien		    subbuf = "";
1732236769Sobrien		    sublen = 0;
1733236769Sobrien	        } else {
1734236769Sobrien		    subbuf = wp + pat->matches[n].rm_so;
1735236769Sobrien		    sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
1736236769Sobrien		}
1737236769Sobrien
1738236769Sobrien		if (sublen > 0) {
1739236769Sobrien		    MAYBE_ADD_SPACE();
1740236769Sobrien		    Buf_AddBytes(buf, sublen, subbuf);
1741236769Sobrien		}
1742236769Sobrien	    } else {
1743236769Sobrien		MAYBE_ADD_SPACE();
1744236769Sobrien		Buf_AddByte(buf, *rp);
1745236769Sobrien	    }
1746236769Sobrien	}
1747236769Sobrien	wp += pat->matches[0].rm_eo;
1748236769Sobrien	if (pat->flags & VAR_SUB_GLOBAL) {
1749236769Sobrien	    flags |= REG_NOTBOL;
1750236769Sobrien	    if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
1751236769Sobrien		MAYBE_ADD_SPACE();
1752236769Sobrien		Buf_AddByte(buf, *wp);
1753236769Sobrien		wp++;
1754236769Sobrien
1755236769Sobrien	    }
1756236769Sobrien	    if (*wp)
1757236769Sobrien		goto tryagain;
1758236769Sobrien	}
1759236769Sobrien	if (*wp) {
1760236769Sobrien	    MAYBE_ADD_SPACE();
1761236769Sobrien	    Buf_AddBytes(buf, strlen(wp), wp);
1762236769Sobrien	}
1763236769Sobrien	break;
1764236769Sobrien    default:
1765236769Sobrien	VarREError(xrv, &pat->re, "Unexpected regex error");
1766236769Sobrien       /* fall through */
1767236769Sobrien    case REG_NOMATCH:
1768236769Sobrien	if (*wp) {
1769236769Sobrien	    MAYBE_ADD_SPACE();
1770236769Sobrien	    Buf_AddBytes(buf,strlen(wp),wp);
1771236769Sobrien	}
1772236769Sobrien	break;
1773236769Sobrien    }
1774236769Sobrien    return(addSpace||added);
1775236769Sobrien}
1776236769Sobrien#endif
1777236769Sobrien
1778236769Sobrien
1779236769Sobrien
1780236769Sobrien/*-
1781236769Sobrien *-----------------------------------------------------------------------
1782236769Sobrien * VarLoopExpand --
1783236769Sobrien *	Implements the :@<temp>@<string>@ modifier of ODE make.
1784236769Sobrien *	We set the temp variable named in pattern.lhs to word and expand
1785236769Sobrien *	pattern.rhs storing the result in the passed buffer.
1786236769Sobrien *
1787236769Sobrien * Input:
1788236769Sobrien *	word		Word to modify
1789236769Sobrien *	addSpace	True if space should be added before
1790236769Sobrien *			other characters
1791236769Sobrien *	buf		Buffer for result
1792236769Sobrien *	pattern		Datafor substitution
1793236769Sobrien *
1794236769Sobrien * Results:
1795236769Sobrien *	TRUE if a space is needed before more characters are added.
1796236769Sobrien *
1797236769Sobrien * Side Effects:
1798236769Sobrien *	None.
1799236769Sobrien *
1800236769Sobrien *-----------------------------------------------------------------------
1801236769Sobrien */
1802236769Sobrienstatic Boolean
1803237578SobrienVarLoopExpand(GNode *ctx MAKE_ATTR_UNUSED,
1804237578Sobrien	      Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
1805236769Sobrien	      char *word, Boolean addSpace, Buffer *buf,
1806236769Sobrien	      void *loopp)
1807236769Sobrien{
1808236769Sobrien    VarLoop_t	*loop = (VarLoop_t *)loopp;
1809236769Sobrien    char *s;
1810236769Sobrien    int slen;
1811236769Sobrien
1812236769Sobrien    if (word && *word) {
1813236769Sobrien        Var_Set(loop->tvar, word, loop->ctxt, VAR_NO_EXPORT);
1814236769Sobrien        s = Var_Subst(NULL, loop->str, loop->ctxt, loop->errnum);
1815236769Sobrien        if (s != NULL && *s != '\0') {
1816236769Sobrien            if (addSpace && *s != '\n')
1817236769Sobrien                Buf_AddByte(buf, ' ');
1818236769Sobrien            Buf_AddBytes(buf, (slen = strlen(s)), s);
1819236769Sobrien            addSpace = (slen > 0 && s[slen - 1] != '\n');
1820236769Sobrien            free(s);
1821236769Sobrien        }
1822236769Sobrien    }
1823236769Sobrien    return addSpace;
1824236769Sobrien}
1825236769Sobrien
1826236769Sobrien
1827236769Sobrien/*-
1828236769Sobrien *-----------------------------------------------------------------------
1829236769Sobrien * VarSelectWords --
1830236769Sobrien *	Implements the :[start..end] modifier.
1831236769Sobrien *	This is a special case of VarModify since we want to be able
1832236769Sobrien *	to scan the list backwards if start > end.
1833236769Sobrien *
1834236769Sobrien * Input:
1835236769Sobrien *	str		String whose words should be trimmed
1836236769Sobrien *	seldata		words to select
1837236769Sobrien *
1838236769Sobrien * Results:
1839236769Sobrien *	A string of all the words selected.
1840236769Sobrien *
1841236769Sobrien * Side Effects:
1842236769Sobrien *	None.
1843236769Sobrien *
1844236769Sobrien *-----------------------------------------------------------------------
1845236769Sobrien */
1846236769Sobrienstatic char *
1847237578SobrienVarSelectWords(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1848236769Sobrien	       const char *str, VarSelectWords_t *seldata)
1849236769Sobrien{
1850236769Sobrien    Buffer  	  buf;		    /* Buffer for the new string */
1851236769Sobrien    Boolean 	  addSpace; 	    /* TRUE if need to add a space to the
1852236769Sobrien				     * buffer before adding the trimmed
1853236769Sobrien				     * word */
1854236769Sobrien    char **av;			    /* word list */
1855236769Sobrien    char *as;			    /* word list memory */
1856236769Sobrien    int ac, i;
1857236769Sobrien    int start, end, step;
1858236769Sobrien
1859236769Sobrien    Buf_Init(&buf, 0);
1860236769Sobrien    addSpace = FALSE;
1861236769Sobrien
1862236769Sobrien    if (vpstate->oneBigWord) {
1863236769Sobrien	/* fake what brk_string() would do if there were only one word */
1864236769Sobrien	ac = 1;
1865236769Sobrien    	av = bmake_malloc((ac + 1) * sizeof(char *));
1866236769Sobrien	as = bmake_strdup(str);
1867236769Sobrien	av[0] = as;
1868236769Sobrien	av[1] = NULL;
1869236769Sobrien    } else {
1870236769Sobrien	av = brk_string(str, &ac, FALSE, &as);
1871236769Sobrien    }
1872236769Sobrien
1873236769Sobrien    /*
1874236769Sobrien     * Now sanitize seldata.
1875236769Sobrien     * If seldata->start or seldata->end are negative, convert them to
1876236769Sobrien     * the positive equivalents (-1 gets converted to argc, -2 gets
1877236769Sobrien     * converted to (argc-1), etc.).
1878236769Sobrien     */
1879236769Sobrien    if (seldata->start < 0)
1880236769Sobrien	seldata->start = ac + seldata->start + 1;
1881236769Sobrien    if (seldata->end < 0)
1882236769Sobrien	seldata->end = ac + seldata->end + 1;
1883236769Sobrien
1884236769Sobrien    /*
1885236769Sobrien     * We avoid scanning more of the list than we need to.
1886236769Sobrien     */
1887236769Sobrien    if (seldata->start > seldata->end) {
1888236769Sobrien	start = MIN(ac, seldata->start) - 1;
1889236769Sobrien	end = MAX(0, seldata->end - 1);
1890236769Sobrien	step = -1;
1891236769Sobrien    } else {
1892236769Sobrien	start = MAX(0, seldata->start - 1);
1893236769Sobrien	end = MIN(ac, seldata->end);
1894236769Sobrien	step = 1;
1895236769Sobrien    }
1896236769Sobrien
1897236769Sobrien    for (i = start;
1898236769Sobrien	 (step < 0 && i >= end) || (step > 0 && i < end);
1899236769Sobrien	 i += step) {
1900236769Sobrien	if (av[i] && *av[i]) {
1901236769Sobrien	    if (addSpace && vpstate->varSpace) {
1902236769Sobrien		Buf_AddByte(&buf, vpstate->varSpace);
1903236769Sobrien	    }
1904236769Sobrien	    Buf_AddBytes(&buf, strlen(av[i]), av[i]);
1905236769Sobrien	    addSpace = TRUE;
1906236769Sobrien	}
1907236769Sobrien    }
1908236769Sobrien
1909236769Sobrien    free(as);
1910236769Sobrien    free(av);
1911236769Sobrien
1912236769Sobrien    return Buf_Destroy(&buf, FALSE);
1913236769Sobrien}
1914236769Sobrien
1915236769Sobrien
1916236769Sobrien/*-
1917236769Sobrien * VarRealpath --
1918236769Sobrien *	Replace each word with the result of realpath()
1919236769Sobrien *	if successful.
1920236769Sobrien */
1921236769Sobrienstatic Boolean
1922237578SobrienVarRealpath(GNode *ctx MAKE_ATTR_UNUSED, Var_Parse_State *vpstate,
1923236769Sobrien	    char *word, Boolean addSpace, Buffer *buf,
1924237578Sobrien	    void *patternp MAKE_ATTR_UNUSED)
1925236769Sobrien{
1926236769Sobrien	struct stat st;
1927236769Sobrien	char rbuf[MAXPATHLEN];
1928236769Sobrien	char *rp;
1929236769Sobrien
1930236769Sobrien	if (addSpace && vpstate->varSpace) {
1931236769Sobrien	    Buf_AddByte(buf, vpstate->varSpace);
1932236769Sobrien	}
1933236769Sobrien	addSpace = TRUE;
1934236769Sobrien	rp = realpath(word, rbuf);
1935236769Sobrien	if (rp && *rp == '/' && stat(rp, &st) == 0)
1936236769Sobrien		word = rp;
1937236769Sobrien
1938236769Sobrien	Buf_AddBytes(buf, strlen(word), word);
1939236769Sobrien	return(addSpace);
1940236769Sobrien}
1941236769Sobrien
1942236769Sobrien/*-
1943236769Sobrien *-----------------------------------------------------------------------
1944236769Sobrien * VarModify --
1945236769Sobrien *	Modify each of the words of the passed string using the given
1946236769Sobrien *	function. Used to implement all modifiers.
1947236769Sobrien *
1948236769Sobrien * Input:
1949236769Sobrien *	str		String whose words should be trimmed
1950236769Sobrien *	modProc		Function to use to modify them
1951236769Sobrien *	datum		Datum to pass it
1952236769Sobrien *
1953236769Sobrien * Results:
1954236769Sobrien *	A string of all the words modified appropriately.
1955236769Sobrien *
1956236769Sobrien * Side Effects:
1957236769Sobrien *	None.
1958236769Sobrien *
1959236769Sobrien *-----------------------------------------------------------------------
1960236769Sobrien */
1961236769Sobrienstatic char *
1962236769SobrienVarModify(GNode *ctx, Var_Parse_State *vpstate,
1963236769Sobrien    const char *str,
1964236769Sobrien    Boolean (*modProc)(GNode *, Var_Parse_State *, char *,
1965236769Sobrien		       Boolean, Buffer *, void *),
1966236769Sobrien    void *datum)
1967236769Sobrien{
1968236769Sobrien    Buffer  	  buf;		    /* Buffer for the new string */
1969236769Sobrien    Boolean 	  addSpace; 	    /* TRUE if need to add a space to the
1970236769Sobrien				     * buffer before adding the trimmed
1971236769Sobrien				     * word */
1972236769Sobrien    char **av;			    /* word list */
1973236769Sobrien    char *as;			    /* word list memory */
1974236769Sobrien    int ac, i;
1975236769Sobrien
1976236769Sobrien    Buf_Init(&buf, 0);
1977236769Sobrien    addSpace = FALSE;
1978236769Sobrien
1979236769Sobrien    if (vpstate->oneBigWord) {
1980236769Sobrien	/* fake what brk_string() would do if there were only one word */
1981236769Sobrien	ac = 1;
1982236769Sobrien    	av = bmake_malloc((ac + 1) * sizeof(char *));
1983236769Sobrien	as = bmake_strdup(str);
1984236769Sobrien	av[0] = as;
1985236769Sobrien	av[1] = NULL;
1986236769Sobrien    } else {
1987236769Sobrien	av = brk_string(str, &ac, FALSE, &as);
1988236769Sobrien    }
1989236769Sobrien
1990236769Sobrien    for (i = 0; i < ac; i++) {
1991236769Sobrien	addSpace = (*modProc)(ctx, vpstate, av[i], addSpace, &buf, datum);
1992236769Sobrien    }
1993236769Sobrien
1994236769Sobrien    free(as);
1995236769Sobrien    free(av);
1996236769Sobrien
1997236769Sobrien    return Buf_Destroy(&buf, FALSE);
1998236769Sobrien}
1999236769Sobrien
2000236769Sobrien
2001236769Sobrienstatic int
2002236769SobrienVarWordCompare(const void *a, const void *b)
2003236769Sobrien{
2004236769Sobrien	int r = strcmp(*(const char * const *)a, *(const char * const *)b);
2005236769Sobrien	return r;
2006236769Sobrien}
2007236769Sobrien
2008236769Sobrien/*-
2009236769Sobrien *-----------------------------------------------------------------------
2010236769Sobrien * VarOrder --
2011236769Sobrien *	Order the words in the string.
2012236769Sobrien *
2013236769Sobrien * Input:
2014236769Sobrien *	str		String whose words should be sorted.
2015236769Sobrien *	otype		How to order: s - sort, x - random.
2016236769Sobrien *
2017236769Sobrien * Results:
2018236769Sobrien *	A string containing the words ordered.
2019236769Sobrien *
2020236769Sobrien * Side Effects:
2021236769Sobrien *	None.
2022236769Sobrien *
2023236769Sobrien *-----------------------------------------------------------------------
2024236769Sobrien */
2025236769Sobrienstatic char *
2026236769SobrienVarOrder(const char *str, const char otype)
2027236769Sobrien{
2028236769Sobrien    Buffer  	  buf;		    /* Buffer for the new string */
2029236769Sobrien    char **av;			    /* word list [first word does not count] */
2030236769Sobrien    char *as;			    /* word list memory */
2031236769Sobrien    int ac, i;
2032236769Sobrien
2033236769Sobrien    Buf_Init(&buf, 0);
2034236769Sobrien
2035236769Sobrien    av = brk_string(str, &ac, FALSE, &as);
2036236769Sobrien
2037236769Sobrien    if (ac > 0)
2038236769Sobrien	switch (otype) {
2039236769Sobrien	case 's':	/* sort alphabetically */
2040236769Sobrien	    qsort(av, ac, sizeof(char *), VarWordCompare);
2041236769Sobrien	    break;
2042236769Sobrien	case 'x':	/* randomize */
2043236769Sobrien	{
2044236769Sobrien	    int rndidx;
2045236769Sobrien	    char *t;
2046236769Sobrien
2047236769Sobrien	    /*
2048236769Sobrien	     * We will use [ac..2] range for mod factors. This will produce
2049236769Sobrien	     * random numbers in [(ac-1)..0] interval, and minimal
2050236769Sobrien	     * reasonable value for mod factor is 2 (the mod 1 will produce
2051236769Sobrien	     * 0 with probability 1).
2052236769Sobrien	     */
2053236769Sobrien	    for (i = ac-1; i > 0; i--) {
2054236769Sobrien		rndidx = random() % (i + 1);
2055236769Sobrien		if (i != rndidx) {
2056236769Sobrien		    t = av[i];
2057236769Sobrien		    av[i] = av[rndidx];
2058236769Sobrien		    av[rndidx] = t;
2059236769Sobrien		}
2060236769Sobrien	    }
2061236769Sobrien	}
2062236769Sobrien	} /* end of switch */
2063236769Sobrien
2064236769Sobrien    for (i = 0; i < ac; i++) {
2065236769Sobrien	Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2066236769Sobrien	if (i != ac - 1)
2067236769Sobrien	    Buf_AddByte(&buf, ' ');
2068236769Sobrien    }
2069236769Sobrien
2070236769Sobrien    free(as);
2071236769Sobrien    free(av);
2072236769Sobrien
2073236769Sobrien    return Buf_Destroy(&buf, FALSE);
2074236769Sobrien}
2075236769Sobrien
2076236769Sobrien
2077236769Sobrien/*-
2078236769Sobrien *-----------------------------------------------------------------------
2079236769Sobrien * VarUniq --
2080236769Sobrien *	Remove adjacent duplicate words.
2081236769Sobrien *
2082236769Sobrien * Input:
2083236769Sobrien *	str		String whose words should be sorted
2084236769Sobrien *
2085236769Sobrien * Results:
2086236769Sobrien *	A string containing the resulting words.
2087236769Sobrien *
2088236769Sobrien * Side Effects:
2089236769Sobrien *	None.
2090236769Sobrien *
2091236769Sobrien *-----------------------------------------------------------------------
2092236769Sobrien */
2093236769Sobrienstatic char *
2094236769SobrienVarUniq(const char *str)
2095236769Sobrien{
2096236769Sobrien    Buffer	  buf;		    /* Buffer for new string */
2097236769Sobrien    char 	**av;		    /* List of words to affect */
2098236769Sobrien    char 	 *as;		    /* Word list memory */
2099236769Sobrien    int 	  ac, i, j;
2100236769Sobrien
2101236769Sobrien    Buf_Init(&buf, 0);
2102236769Sobrien    av = brk_string(str, &ac, FALSE, &as);
2103236769Sobrien
2104236769Sobrien    if (ac > 1) {
2105236769Sobrien	for (j = 0, i = 1; i < ac; i++)
2106236769Sobrien	    if (strcmp(av[i], av[j]) != 0 && (++j != i))
2107236769Sobrien		av[j] = av[i];
2108236769Sobrien	ac = j + 1;
2109236769Sobrien    }
2110236769Sobrien
2111236769Sobrien    for (i = 0; i < ac; i++) {
2112236769Sobrien	Buf_AddBytes(&buf, strlen(av[i]), av[i]);
2113236769Sobrien	if (i != ac - 1)
2114236769Sobrien	    Buf_AddByte(&buf, ' ');
2115236769Sobrien    }
2116236769Sobrien
2117236769Sobrien    free(as);
2118236769Sobrien    free(av);
2119236769Sobrien
2120236769Sobrien    return Buf_Destroy(&buf, FALSE);
2121236769Sobrien}
2122236769Sobrien
2123236769Sobrien
2124236769Sobrien/*-
2125236769Sobrien *-----------------------------------------------------------------------
2126236769Sobrien * VarGetPattern --
2127236769Sobrien *	Pass through the tstr looking for 1) escaped delimiters,
2128236769Sobrien *	'$'s and backslashes (place the escaped character in
2129236769Sobrien *	uninterpreted) and 2) unescaped $'s that aren't before
2130236769Sobrien *	the delimiter (expand the variable substitution unless flags
2131236769Sobrien *	has VAR_NOSUBST set).
2132236769Sobrien *	Return the expanded string or NULL if the delimiter was missing
2133236769Sobrien *	If pattern is specified, handle escaped ampersands, and replace
2134236769Sobrien *	unescaped ampersands with the lhs of the pattern.
2135236769Sobrien *
2136236769Sobrien * Results:
2137236769Sobrien *	A string of all the words modified appropriately.
2138236769Sobrien *	If length is specified, return the string length of the buffer
2139236769Sobrien *	If flags is specified and the last character of the pattern is a
2140236769Sobrien *	$ set the VAR_MATCH_END bit of flags.
2141236769Sobrien *
2142236769Sobrien * Side Effects:
2143236769Sobrien *	None.
2144236769Sobrien *-----------------------------------------------------------------------
2145236769Sobrien */
2146236769Sobrienstatic char *
2147237578SobrienVarGetPattern(GNode *ctxt, Var_Parse_State *vpstate MAKE_ATTR_UNUSED,
2148236769Sobrien	      int errnum, const char **tstr, int delim, int *flags,
2149236769Sobrien	      int *length, VarPattern *pattern)
2150236769Sobrien{
2151236769Sobrien    const char *cp;
2152236769Sobrien    char *rstr;
2153236769Sobrien    Buffer buf;
2154236769Sobrien    int junk;
2155236769Sobrien
2156236769Sobrien    Buf_Init(&buf, 0);
2157236769Sobrien    if (length == NULL)
2158236769Sobrien	length = &junk;
2159236769Sobrien
2160236769Sobrien#define IS_A_MATCH(cp, delim) \
2161236769Sobrien    ((cp[0] == '\\') && ((cp[1] == delim) ||  \
2162236769Sobrien     (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
2163236769Sobrien
2164236769Sobrien    /*
2165236769Sobrien     * Skim through until the matching delimiter is found;
2166236769Sobrien     * pick up variable substitutions on the way. Also allow
2167236769Sobrien     * backslashes to quote the delimiter, $, and \, but don't
2168236769Sobrien     * touch other backslashes.
2169236769Sobrien     */
2170236769Sobrien    for (cp = *tstr; *cp && (*cp != delim); cp++) {
2171236769Sobrien	if (IS_A_MATCH(cp, delim)) {
2172236769Sobrien	    Buf_AddByte(&buf, cp[1]);
2173236769Sobrien	    cp++;
2174236769Sobrien	} else if (*cp == '$') {
2175236769Sobrien	    if (cp[1] == delim) {
2176236769Sobrien		if (flags == NULL)
2177236769Sobrien		    Buf_AddByte(&buf, *cp);
2178236769Sobrien		else
2179236769Sobrien		    /*
2180236769Sobrien		     * Unescaped $ at end of pattern => anchor
2181236769Sobrien		     * pattern at end.
2182236769Sobrien		     */
2183236769Sobrien		    *flags |= VAR_MATCH_END;
2184236769Sobrien	    } else {
2185236769Sobrien		if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
2186236769Sobrien		    char   *cp2;
2187236769Sobrien		    int     len;
2188236769Sobrien		    void   *freeIt;
2189236769Sobrien
2190236769Sobrien		    /*
2191236769Sobrien		     * If unescaped dollar sign not before the
2192236769Sobrien		     * delimiter, assume it's a variable
2193236769Sobrien		     * substitution and recurse.
2194236769Sobrien		     */
2195236769Sobrien		    cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2196236769Sobrien		    Buf_AddBytes(&buf, strlen(cp2), cp2);
2197236769Sobrien		    if (freeIt)
2198236769Sobrien			free(freeIt);
2199236769Sobrien		    cp += len - 1;
2200236769Sobrien		} else {
2201236769Sobrien		    const char *cp2 = &cp[1];
2202236769Sobrien
2203236769Sobrien		    if (*cp2 == PROPEN || *cp2 == BROPEN) {
2204236769Sobrien			/*
2205236769Sobrien			 * Find the end of this variable reference
2206236769Sobrien			 * and suck it in without further ado.
2207236769Sobrien			 * It will be interperated later.
2208236769Sobrien			 */
2209236769Sobrien			int have = *cp2;
2210236769Sobrien			int want = (*cp2 == PROPEN) ? PRCLOSE : BRCLOSE;
2211236769Sobrien			int depth = 1;
2212236769Sobrien
2213236769Sobrien			for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
2214236769Sobrien			    if (cp2[-1] != '\\') {
2215236769Sobrien				if (*cp2 == have)
2216236769Sobrien				    ++depth;
2217236769Sobrien				if (*cp2 == want)
2218236769Sobrien				    --depth;
2219236769Sobrien			    }
2220236769Sobrien			}
2221236769Sobrien			Buf_AddBytes(&buf, cp2 - cp, cp);
2222236769Sobrien			cp = --cp2;
2223236769Sobrien		    } else
2224236769Sobrien			Buf_AddByte(&buf, *cp);
2225236769Sobrien		}
2226236769Sobrien	    }
2227236769Sobrien	}
2228236769Sobrien	else if (pattern && *cp == '&')
2229236769Sobrien	    Buf_AddBytes(&buf, pattern->leftLen, pattern->lhs);
2230236769Sobrien	else
2231236769Sobrien	    Buf_AddByte(&buf, *cp);
2232236769Sobrien    }
2233236769Sobrien
2234236769Sobrien    if (*cp != delim) {
2235236769Sobrien	*tstr = cp;
2236236769Sobrien	*length = 0;
2237236769Sobrien	return NULL;
2238236769Sobrien    }
2239236769Sobrien
2240236769Sobrien    *tstr = ++cp;
2241236769Sobrien    *length = Buf_Size(&buf);
2242236769Sobrien    rstr = Buf_Destroy(&buf, FALSE);
2243236769Sobrien    if (DEBUG(VAR))
2244236769Sobrien	fprintf(debug_file, "Modifier pattern: \"%s\"\n", rstr);
2245236769Sobrien    return rstr;
2246236769Sobrien}
2247236769Sobrien
2248236769Sobrien/*-
2249236769Sobrien *-----------------------------------------------------------------------
2250236769Sobrien * VarQuote --
2251236769Sobrien *	Quote shell meta-characters in the string
2252236769Sobrien *
2253236769Sobrien * Results:
2254236769Sobrien *	The quoted string
2255236769Sobrien *
2256236769Sobrien * Side Effects:
2257236769Sobrien *	None.
2258236769Sobrien *
2259236769Sobrien *-----------------------------------------------------------------------
2260236769Sobrien */
2261236769Sobrienstatic char *
2262236769SobrienVarQuote(char *str)
2263236769Sobrien{
2264236769Sobrien
2265236769Sobrien    Buffer  	  buf;
2266236769Sobrien    /* This should cover most shells :-( */
2267236769Sobrien    static const char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
2268236769Sobrien    const char	*newline;
2269236769Sobrien    size_t len, nlen;
2270236769Sobrien
2271236769Sobrien    if ((newline = Shell_GetNewline()) == NULL)
2272236769Sobrien	    newline = "\\\n";
2273236769Sobrien    nlen = strlen(newline);
2274236769Sobrien
2275236769Sobrien    Buf_Init(&buf, 0);
2276236769Sobrien    while (*str != '\0') {
2277236769Sobrien	if ((len = strcspn(str, meta)) != 0) {
2278236769Sobrien	    Buf_AddBytes(&buf, len, str);
2279236769Sobrien	    str += len;
2280236769Sobrien	} else if (*str == '\n') {
2281236769Sobrien	    Buf_AddBytes(&buf, nlen, newline);
2282236769Sobrien	    ++str;
2283236769Sobrien	} else {
2284236769Sobrien	    Buf_AddByte(&buf, '\\');
2285236769Sobrien	    Buf_AddByte(&buf, *str);
2286236769Sobrien	    ++str;
2287236769Sobrien	}
2288236769Sobrien    }
2289236769Sobrien    str = Buf_Destroy(&buf, FALSE);
2290236769Sobrien    if (DEBUG(VAR))
2291236769Sobrien	fprintf(debug_file, "QuoteMeta: [%s]\n", str);
2292236769Sobrien    return str;
2293236769Sobrien}
2294236769Sobrien
2295236769Sobrien/*-
2296236769Sobrien *-----------------------------------------------------------------------
2297236769Sobrien * VarHash --
2298236769Sobrien *      Hash the string using the MurmurHash3 algorithm.
2299236769Sobrien *      Output is computed using 32bit Little Endian arithmetic.
2300236769Sobrien *
2301236769Sobrien * Input:
2302236769Sobrien *	str		String to modify
2303236769Sobrien *
2304236769Sobrien * Results:
2305236769Sobrien *      Hash value of str, encoded as 8 hex digits.
2306236769Sobrien *
2307236769Sobrien * Side Effects:
2308236769Sobrien *      None.
2309236769Sobrien *
2310236769Sobrien *-----------------------------------------------------------------------
2311236769Sobrien */
2312236769Sobrienstatic char *
2313236769SobrienVarHash(char *str)
2314236769Sobrien{
2315236769Sobrien    static const char    hexdigits[16] = "0123456789abcdef";
2316236769Sobrien    Buffer         buf;
2317236769Sobrien    size_t         len, len2;
2318236769Sobrien    unsigned char  *ustr = (unsigned char *)str;
2319236769Sobrien    uint32_t       h, k, c1, c2;
2320236769Sobrien    int            done;
2321236769Sobrien
2322236769Sobrien    done = 1;
2323236769Sobrien    h  = 0x971e137bU;
2324236769Sobrien    c1 = 0x95543787U;
2325236769Sobrien    c2 = 0x2ad7eb25U;
2326236769Sobrien    len2 = strlen(str);
2327236769Sobrien
2328236769Sobrien    for (len = len2; len; ) {
2329236769Sobrien	k = 0;
2330236769Sobrien	switch (len) {
2331236769Sobrien	default:
2332236769Sobrien	    k = (ustr[3] << 24) | (ustr[2] << 16) | (ustr[1] << 8) | ustr[0];
2333236769Sobrien	    len -= 4;
2334236769Sobrien	    ustr += 4;
2335236769Sobrien	    break;
2336236769Sobrien	case 3:
2337236769Sobrien	    k |= (ustr[2] << 16);
2338236769Sobrien	case 2:
2339236769Sobrien	    k |= (ustr[1] << 8);
2340236769Sobrien	case 1:
2341236769Sobrien	    k |= ustr[0];
2342236769Sobrien	    len = 0;
2343236769Sobrien	}
2344236769Sobrien	c1 = c1 * 5 + 0x7b7d159cU;
2345236769Sobrien	c2 = c2 * 5 + 0x6bce6396U;
2346236769Sobrien	k *= c1;
2347236769Sobrien	k = (k << 11) ^ (k >> 21);
2348236769Sobrien	k *= c2;
2349236769Sobrien	h = (h << 13) ^ (h >> 19);
2350236769Sobrien	h = h * 5 + 0x52dce729U;
2351236769Sobrien	h ^= k;
2352236769Sobrien   } while (!done);
2353236769Sobrien   h ^= len2;
2354236769Sobrien   h *= 0x85ebca6b;
2355236769Sobrien   h ^= h >> 13;
2356236769Sobrien   h *= 0xc2b2ae35;
2357236769Sobrien   h ^= h >> 16;
2358236769Sobrien
2359236769Sobrien   Buf_Init(&buf, 0);
2360236769Sobrien   for (len = 0; len < 8; ++len) {
2361236769Sobrien       Buf_AddByte(&buf, hexdigits[h & 15]);
2362236769Sobrien       h >>= 4;
2363236769Sobrien   }
2364236769Sobrien
2365236769Sobrien   return Buf_Destroy(&buf, FALSE);
2366236769Sobrien}
2367236769Sobrien
2368236769Sobrienstatic char *
2369236769SobrienVarStrftime(const char *fmt, int zulu)
2370236769Sobrien{
2371236769Sobrien    char buf[BUFSIZ];
2372236769Sobrien    time_t utc;
2373236769Sobrien
2374236769Sobrien    time(&utc);
2375236769Sobrien    if (!*fmt)
2376236769Sobrien	fmt = "%c";
2377236769Sobrien    strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&utc) : localtime(&utc));
2378236769Sobrien
2379236769Sobrien    buf[sizeof(buf) - 1] = '\0';
2380236769Sobrien    return bmake_strdup(buf);
2381236769Sobrien}
2382236769Sobrien
2383236769Sobrien/*
2384236769Sobrien * Now we need to apply any modifiers the user wants applied.
2385236769Sobrien * These are:
2386236769Sobrien *  	  :M<pattern>	words which match the given <pattern>.
2387236769Sobrien *  			<pattern> is of the standard file
2388236769Sobrien *  			wildcarding form.
2389236769Sobrien *  	  :N<pattern>	words which do not match the given <pattern>.
2390236769Sobrien *  	  :S<d><pat1><d><pat2><d>[1gW]
2391236769Sobrien *  			Substitute <pat2> for <pat1> in the value
2392236769Sobrien *  	  :C<d><pat1><d><pat2><d>[1gW]
2393236769Sobrien *  			Substitute <pat2> for regex <pat1> in the value
2394236769Sobrien *  	  :H		Substitute the head of each word
2395236769Sobrien *  	  :T		Substitute the tail of each word
2396236769Sobrien *  	  :E		Substitute the extension (minus '.') of
2397236769Sobrien *  			each word
2398236769Sobrien *  	  :R		Substitute the root of each word
2399236769Sobrien *  			(pathname minus the suffix).
2400236769Sobrien *	  :O		("Order") Alphabeticaly sort words in variable.
2401236769Sobrien *	  :Ox		("intermiX") Randomize words in variable.
2402236769Sobrien *	  :u		("uniq") Remove adjacent duplicate words.
2403236769Sobrien *	  :tu		Converts the variable contents to uppercase.
2404236769Sobrien *	  :tl		Converts the variable contents to lowercase.
2405236769Sobrien *	  :ts[c]	Sets varSpace - the char used to
2406236769Sobrien *			separate words to 'c'. If 'c' is
2407236769Sobrien *			omitted then no separation is used.
2408236769Sobrien *	  :tW		Treat the variable contents as a single
2409236769Sobrien *			word, even if it contains spaces.
2410236769Sobrien *			(Mnemonic: one big 'W'ord.)
2411236769Sobrien *	  :tw		Treat the variable contents as multiple
2412236769Sobrien *			space-separated words.
2413236769Sobrien *			(Mnemonic: many small 'w'ords.)
2414236769Sobrien *	  :[index]	Select a single word from the value.
2415236769Sobrien *	  :[start..end]	Select multiple words from the value.
2416236769Sobrien *	  :[*] or :[0]	Select the entire value, as a single
2417236769Sobrien *			word.  Equivalent to :tW.
2418236769Sobrien *	  :[@]		Select the entire value, as multiple
2419236769Sobrien *			words.	Undoes the effect of :[*].
2420236769Sobrien *			Equivalent to :tw.
2421236769Sobrien *	  :[#]		Returns the number of words in the value.
2422236769Sobrien *
2423236769Sobrien *	  :?<true-value>:<false-value>
2424236769Sobrien *			If the variable evaluates to true, return
2425236769Sobrien *			true value, else return the second value.
2426236769Sobrien *    	  :lhs=rhs  	Like :S, but the rhs goes to the end of
2427236769Sobrien *    			the invocation.
2428236769Sobrien *	  :sh		Treat the current value as a command
2429236769Sobrien *			to be run, new value is its output.
2430236769Sobrien * The following added so we can handle ODE makefiles.
2431236769Sobrien *	  :@<tmpvar>@<newval>@
2432236769Sobrien *			Assign a temporary local variable <tmpvar>
2433236769Sobrien *			to the current value of each word in turn
2434236769Sobrien *			and replace each word with the result of
2435236769Sobrien *			evaluating <newval>
2436236769Sobrien *	  :D<newval>	Use <newval> as value if variable defined
2437236769Sobrien *	  :U<newval>	Use <newval> as value if variable undefined
2438236769Sobrien *	  :L		Use the name of the variable as the value.
2439236769Sobrien *	  :P		Use the path of the node that has the same
2440236769Sobrien *			name as the variable as the value.  This
2441236769Sobrien *			basically includes an implied :L so that
2442236769Sobrien *			the common method of refering to the path
2443236769Sobrien *			of your dependent 'x' in a rule is to use
2444236769Sobrien *			the form '${x:P}'.
2445236769Sobrien *	  :!<cmd>!	Run cmd much the same as :sh run's the
2446236769Sobrien *			current value of the variable.
2447236769Sobrien * The ::= modifiers, actually assign a value to the variable.
2448236769Sobrien * Their main purpose is in supporting modifiers of .for loop
2449236769Sobrien * iterators and other obscure uses.  They always expand to
2450236769Sobrien * nothing.  In a target rule that would otherwise expand to an
2451236769Sobrien * empty line they can be preceded with @: to keep make happy.
2452236769Sobrien * Eg.
2453236769Sobrien *
2454236769Sobrien * foo:	.USE
2455236769Sobrien * .for i in ${.TARGET} ${.TARGET:R}.gz
2456236769Sobrien * 	@: ${t::=$i}
2457236769Sobrien *	@echo blah ${t:T}
2458236769Sobrien * .endfor
2459236769Sobrien *
2460236769Sobrien *	  ::=<str>	Assigns <str> as the new value of variable.
2461236769Sobrien *	  ::?=<str>	Assigns <str> as value of variable if
2462236769Sobrien *			it was not already set.
2463236769Sobrien *	  ::+=<str>	Appends <str> to variable.
2464236769Sobrien *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
2465236769Sobrien *			variable.
2466236769Sobrien */
2467236769Sobrien
2468236769Sobrien/* we now have some modifiers with long names */
2469236769Sobrien#define STRMOD_MATCH(s, want, n) \
2470236769Sobrien    (strncmp(s, want, n) == 0 && (s[n] == endc || s[n] == ':'))
2471236769Sobrien
2472236769Sobrienstatic char *
2473236769SobrienApplyModifiers(char *nstr, const char *tstr,
2474236769Sobrien	       int startc, int endc,
2475236769Sobrien	       Var *v, GNode *ctxt, Boolean errnum,
2476236769Sobrien	       int *lengthPtr, void **freePtr)
2477236769Sobrien{
2478236769Sobrien    const char 	   *start;
2479236769Sobrien    const char     *cp;    	/* Secondary pointer into str (place marker
2480236769Sobrien				 * for tstr) */
2481236769Sobrien    char	   *newStr;	/* New value to return */
2482236769Sobrien    char	    termc;	/* Character which terminated scan */
2483236769Sobrien    int             cnt;	/* Used to count brace pairs when variable in
2484236769Sobrien				 * in parens or braces */
2485236769Sobrien    char	delim;
2486236769Sobrien    int		modifier;	/* that we are processing */
2487236769Sobrien    Var_Parse_State parsestate; /* Flags passed to helper functions */
2488236769Sobrien
2489236769Sobrien    delim = '\0';
2490236769Sobrien    parsestate.oneBigWord = FALSE;
2491236769Sobrien    parsestate.varSpace = ' ';	/* word separator */
2492236769Sobrien
2493236769Sobrien    start = cp = tstr;
2494236769Sobrien
2495236769Sobrien    while (*tstr && *tstr != endc) {
2496236769Sobrien
2497236769Sobrien	if (*tstr == '$') {
2498236769Sobrien	    /*
2499236769Sobrien	     * We may have some complex modifiers in a variable.
2500236769Sobrien	     */
2501236769Sobrien	    void *freeIt;
2502236769Sobrien	    char *rval;
2503236769Sobrien	    int rlen;
2504236769Sobrien	    int c;
2505236769Sobrien
2506236769Sobrien	    rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
2507236769Sobrien
2508236769Sobrien	    /*
2509236769Sobrien	     * If we have not parsed up to endc or ':',
2510236769Sobrien	     * we are not interested.
2511236769Sobrien	     */
2512236769Sobrien	    if (rval != NULL && *rval &&
2513236769Sobrien		(c = tstr[rlen]) != '\0' &&
2514236769Sobrien		c != ':' &&
2515236769Sobrien		c != endc) {
2516236769Sobrien		if (freeIt)
2517236769Sobrien		    free(freeIt);
2518236769Sobrien		goto apply_mods;
2519236769Sobrien	    }
2520236769Sobrien
2521236769Sobrien	    if (DEBUG(VAR)) {
2522236769Sobrien		fprintf(debug_file, "Got '%s' from '%.*s'%.*s\n",
2523236769Sobrien		       rval, rlen, tstr, rlen, tstr + rlen);
2524236769Sobrien	    }
2525236769Sobrien
2526236769Sobrien	    tstr += rlen;
2527236769Sobrien
2528236769Sobrien	    if (rval != NULL && *rval) {
2529236769Sobrien		int used;
2530236769Sobrien
2531236769Sobrien		nstr = ApplyModifiers(nstr, rval,
2532236769Sobrien				      0, 0,
2533236769Sobrien				      v, ctxt, errnum, &used, freePtr);
2534236769Sobrien		if (nstr == var_Error
2535236769Sobrien		    || (nstr == varNoError && errnum == 0)
2536236769Sobrien		    || strlen(rval) != (size_t) used) {
2537236769Sobrien		    if (freeIt)
2538236769Sobrien			free(freeIt);
2539236769Sobrien		    goto out;		/* error already reported */
2540236769Sobrien		}
2541236769Sobrien	    }
2542236769Sobrien	    if (freeIt)
2543236769Sobrien		free(freeIt);
2544236769Sobrien	    if (*tstr == ':')
2545236769Sobrien		tstr++;
2546236769Sobrien	    else if (!*tstr && endc) {
2547236769Sobrien		Error("Unclosed variable specification after complex modifier (expecting '%c') for %s", endc, v->name);
2548236769Sobrien		goto out;
2549236769Sobrien	    }
2550236769Sobrien	    continue;
2551236769Sobrien	}
2552236769Sobrien    apply_mods:
2553236769Sobrien	if (DEBUG(VAR)) {
2554246223Ssjg	    fprintf(debug_file, "Applying[%s] :%c to \"%s\"\n", v->name,
2555246223Ssjg		*tstr, nstr);
2556236769Sobrien	}
2557236769Sobrien	newStr = var_Error;
2558236769Sobrien	switch ((modifier = *tstr)) {
2559236769Sobrien	case ':':
2560236769Sobrien	    {
2561236769Sobrien		if (tstr[1] == '=' ||
2562236769Sobrien		    (tstr[2] == '=' &&
2563236769Sobrien		     (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
2564236769Sobrien		    /*
2565236769Sobrien		     * "::=", "::!=", "::+=", or "::?="
2566236769Sobrien		     */
2567236769Sobrien		    GNode *v_ctxt;		/* context where v belongs */
2568236769Sobrien		    const char *emsg;
2569236769Sobrien		    char *sv_name;
2570236769Sobrien		    VarPattern	pattern;
2571236769Sobrien		    int	how;
2572236769Sobrien
2573236769Sobrien		    if (v->name[0] == 0)
2574236769Sobrien			goto bad_modifier;
2575236769Sobrien
2576236769Sobrien		    v_ctxt = ctxt;
2577236769Sobrien		    sv_name = NULL;
2578236769Sobrien		    ++tstr;
2579236769Sobrien		    if (v->flags & VAR_JUNK) {
2580236769Sobrien			/*
2581236769Sobrien			 * We need to bmake_strdup() it incase
2582236769Sobrien			 * VarGetPattern() recurses.
2583236769Sobrien			 */
2584236769Sobrien			sv_name = v->name;
2585236769Sobrien			v->name = bmake_strdup(v->name);
2586236769Sobrien		    } else if (ctxt != VAR_GLOBAL) {
2587236769Sobrien			Var *gv = VarFind(v->name, ctxt, 0);
2588236769Sobrien			if (gv == NULL)
2589236769Sobrien			    v_ctxt = VAR_GLOBAL;
2590236769Sobrien			else
2591236769Sobrien			    VarFreeEnv(gv, TRUE);
2592236769Sobrien		    }
2593236769Sobrien
2594236769Sobrien		    switch ((how = *tstr)) {
2595236769Sobrien		    case '+':
2596236769Sobrien		    case '?':
2597236769Sobrien		    case '!':
2598236769Sobrien			cp = &tstr[2];
2599236769Sobrien			break;
2600236769Sobrien		    default:
2601236769Sobrien			cp = ++tstr;
2602236769Sobrien			break;
2603236769Sobrien		    }
2604236769Sobrien		    delim = startc == PROPEN ? PRCLOSE : BRCLOSE;
2605236769Sobrien		    pattern.flags = 0;
2606236769Sobrien
2607236769Sobrien		    pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2608236769Sobrien						&cp, delim, NULL,
2609236769Sobrien						&pattern.rightLen,
2610236769Sobrien						NULL);
2611236769Sobrien		    if (v->flags & VAR_JUNK) {
2612236769Sobrien			/* restore original name */
2613236769Sobrien			free(v->name);
2614236769Sobrien			v->name = sv_name;
2615236769Sobrien		    }
2616236769Sobrien		    if (pattern.rhs == NULL)
2617236769Sobrien			goto cleanup;
2618236769Sobrien
2619236769Sobrien		    termc = *--cp;
2620236769Sobrien		    delim = '\0';
2621236769Sobrien
2622236769Sobrien		    switch (how) {
2623236769Sobrien		    case '+':
2624236769Sobrien			Var_Append(v->name, pattern.rhs, v_ctxt);
2625236769Sobrien			break;
2626236769Sobrien		    case '!':
2627236769Sobrien			newStr = Cmd_Exec(pattern.rhs, &emsg);
2628236769Sobrien			if (emsg)
2629236769Sobrien			    Error(emsg, nstr);
2630236769Sobrien			else
2631236769Sobrien			    Var_Set(v->name, newStr,  v_ctxt, 0);
2632236769Sobrien			if (newStr)
2633236769Sobrien			    free(newStr);
2634236769Sobrien			break;
2635236769Sobrien		    case '?':
2636236769Sobrien			if ((v->flags & VAR_JUNK) == 0)
2637236769Sobrien			    break;
2638236769Sobrien			/* FALLTHROUGH */
2639236769Sobrien		    default:
2640236769Sobrien			Var_Set(v->name, pattern.rhs, v_ctxt, 0);
2641236769Sobrien			break;
2642236769Sobrien		    }
2643236769Sobrien		    free(UNCONST(pattern.rhs));
2644236769Sobrien		    newStr = var_Error;
2645236769Sobrien		    break;
2646236769Sobrien		}
2647236769Sobrien		goto default_case; /* "::<unrecognised>" */
2648236769Sobrien	    }
2649236769Sobrien	case '@':
2650236769Sobrien	    {
2651236769Sobrien		VarLoop_t	loop;
2652236769Sobrien		int flags = VAR_NOSUBST;
2653236769Sobrien
2654236769Sobrien		cp = ++tstr;
2655236769Sobrien		delim = '@';
2656236769Sobrien		if ((loop.tvar = VarGetPattern(ctxt, &parsestate, errnum,
2657236769Sobrien					       &cp, delim,
2658236769Sobrien					       &flags, &loop.tvarLen,
2659236769Sobrien					       NULL)) == NULL)
2660236769Sobrien		    goto cleanup;
2661236769Sobrien
2662236769Sobrien		if ((loop.str = VarGetPattern(ctxt, &parsestate, errnum,
2663236769Sobrien					      &cp, delim,
2664236769Sobrien					      &flags, &loop.strLen,
2665236769Sobrien					      NULL)) == NULL)
2666236769Sobrien		    goto cleanup;
2667236769Sobrien
2668236769Sobrien		termc = *cp;
2669236769Sobrien		delim = '\0';
2670236769Sobrien
2671236769Sobrien		loop.errnum = errnum;
2672236769Sobrien		loop.ctxt = ctxt;
2673236769Sobrien		newStr = VarModify(ctxt, &parsestate, nstr, VarLoopExpand,
2674236769Sobrien				   &loop);
2675236769Sobrien		free(loop.tvar);
2676236769Sobrien		free(loop.str);
2677236769Sobrien		break;
2678236769Sobrien	    }
2679250164Ssjg	case 'U':
2680250164Ssjg#ifdef MAKE_FREEBSD_UL
2681250164Ssjg	    if (FreeBSD_UL) {
2682250164Ssjg		int nc = tstr[1];
2683250164Ssjg
2684250164Ssjg		/* we have to be careful, since :U is used internally */
2685250164Ssjg		if (nc == ':' || nc == endc) {
2686250164Ssjg		    char *dp = bmake_strdup(nstr);
2687250164Ssjg		    for (newStr = dp; *dp; dp++)
2688250164Ssjg			*dp = toupper((unsigned char)*dp);
2689250164Ssjg		    cp = tstr + 1;
2690250164Ssjg		    termc = *cp;
2691250164Ssjg		    break;		/* yes inside the conditional */
2692250164Ssjg		}
2693250164Ssjg		/* FALLTHROUGH */
2694250164Ssjg	    }
2695250164Ssjg#endif
2696236769Sobrien	case 'D':
2697236769Sobrien	    {
2698236769Sobrien		Buffer  buf;    	/* Buffer for patterns */
2699236769Sobrien		int	    wantit;	/* want data in buffer */
2700236769Sobrien
2701236769Sobrien		/*
2702236769Sobrien		 * Pass through tstr looking for 1) escaped delimiters,
2703236769Sobrien		 * '$'s and backslashes (place the escaped character in
2704236769Sobrien		 * uninterpreted) and 2) unescaped $'s that aren't before
2705236769Sobrien		 * the delimiter (expand the variable substitution).
2706236769Sobrien		 * The result is left in the Buffer buf.
2707236769Sobrien		 */
2708236769Sobrien		Buf_Init(&buf, 0);
2709236769Sobrien		for (cp = tstr + 1;
2710236769Sobrien		     *cp != endc && *cp != ':' && *cp != '\0';
2711236769Sobrien		     cp++) {
2712236769Sobrien		    if ((*cp == '\\') &&
2713236769Sobrien			((cp[1] == ':') ||
2714236769Sobrien			 (cp[1] == '$') ||
2715236769Sobrien			 (cp[1] == endc) ||
2716236769Sobrien			 (cp[1] == '\\')))
2717236769Sobrien			{
2718236769Sobrien			    Buf_AddByte(&buf, cp[1]);
2719236769Sobrien			    cp++;
2720236769Sobrien			} else if (*cp == '$') {
2721236769Sobrien			    /*
2722236769Sobrien			     * If unescaped dollar sign, assume it's a
2723236769Sobrien			     * variable substitution and recurse.
2724236769Sobrien			     */
2725236769Sobrien			    char    *cp2;
2726236769Sobrien			    int	    len;
2727236769Sobrien			    void    *freeIt;
2728236769Sobrien
2729236769Sobrien			    cp2 = Var_Parse(cp, ctxt, errnum, &len, &freeIt);
2730236769Sobrien			    Buf_AddBytes(&buf, strlen(cp2), cp2);
2731236769Sobrien			    if (freeIt)
2732236769Sobrien				free(freeIt);
2733236769Sobrien			    cp += len - 1;
2734236769Sobrien			} else {
2735236769Sobrien			    Buf_AddByte(&buf, *cp);
2736236769Sobrien			}
2737236769Sobrien		}
2738236769Sobrien
2739236769Sobrien		termc = *cp;
2740236769Sobrien
2741236769Sobrien		if (*tstr == 'U')
2742236769Sobrien		    wantit = ((v->flags & VAR_JUNK) != 0);
2743236769Sobrien		else
2744236769Sobrien		    wantit = ((v->flags & VAR_JUNK) == 0);
2745236769Sobrien		if ((v->flags & VAR_JUNK) != 0)
2746236769Sobrien		    v->flags |= VAR_KEEP;
2747236769Sobrien		if (wantit) {
2748236769Sobrien		    newStr = Buf_Destroy(&buf, FALSE);
2749236769Sobrien		} else {
2750236769Sobrien		    newStr = nstr;
2751236769Sobrien		    Buf_Destroy(&buf, TRUE);
2752236769Sobrien		}
2753236769Sobrien		break;
2754236769Sobrien	    }
2755236769Sobrien	case 'L':
2756250164Ssjg#ifdef MAKE_FREEBSD_UL
2757250164Ssjg	    if (FreeBSD_UL) {
2758250164Ssjg		char *dp = bmake_strdup(nstr);
2759250164Ssjg		for (newStr = dp; *dp; dp++)
2760250164Ssjg		    *dp = tolower((unsigned char)*dp);
2761250164Ssjg		cp = tstr + 1;
2762250164Ssjg		termc = *cp;
2763250164Ssjg		break;
2764250164Ssjg	    }
2765250164Ssjg	    /* FALLTHROUGH */
2766250164Ssjg#endif
2767236769Sobrien	    {
2768236769Sobrien		if ((v->flags & VAR_JUNK) != 0)
2769236769Sobrien		    v->flags |= VAR_KEEP;
2770236769Sobrien		newStr = bmake_strdup(v->name);
2771236769Sobrien		cp = ++tstr;
2772236769Sobrien		termc = *tstr;
2773236769Sobrien		break;
2774236769Sobrien	    }
2775236769Sobrien	case 'P':
2776236769Sobrien	    {
2777236769Sobrien		GNode *gn;
2778236769Sobrien
2779236769Sobrien		if ((v->flags & VAR_JUNK) != 0)
2780236769Sobrien		    v->flags |= VAR_KEEP;
2781236769Sobrien		gn = Targ_FindNode(v->name, TARG_NOCREATE);
2782236769Sobrien		if (gn == NULL || gn->type & OP_NOPATH) {
2783236769Sobrien		    newStr = NULL;
2784236769Sobrien		} else if (gn->path) {
2785236769Sobrien		    newStr = bmake_strdup(gn->path);
2786236769Sobrien		} else {
2787236769Sobrien		    newStr = Dir_FindFile(v->name, Suff_FindPath(gn));
2788236769Sobrien		}
2789236769Sobrien		if (!newStr) {
2790236769Sobrien		    newStr = bmake_strdup(v->name);
2791236769Sobrien		}
2792236769Sobrien		cp = ++tstr;
2793236769Sobrien		termc = *tstr;
2794236769Sobrien		break;
2795236769Sobrien	    }
2796236769Sobrien	case '!':
2797236769Sobrien	    {
2798236769Sobrien		const char *emsg;
2799236769Sobrien		VarPattern 	    pattern;
2800236769Sobrien		pattern.flags = 0;
2801236769Sobrien
2802236769Sobrien		delim = '!';
2803236769Sobrien
2804236769Sobrien		cp = ++tstr;
2805236769Sobrien		if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
2806236769Sobrien						 &cp, delim,
2807236769Sobrien						 NULL, &pattern.rightLen,
2808236769Sobrien						 NULL)) == NULL)
2809236769Sobrien		    goto cleanup;
2810236769Sobrien		newStr = Cmd_Exec(pattern.rhs, &emsg);
2811236769Sobrien		free(UNCONST(pattern.rhs));
2812236769Sobrien		if (emsg)
2813236769Sobrien		    Error(emsg, nstr);
2814236769Sobrien		termc = *cp;
2815236769Sobrien		delim = '\0';
2816236769Sobrien		if (v->flags & VAR_JUNK) {
2817236769Sobrien		    v->flags |= VAR_KEEP;
2818236769Sobrien		}
2819236769Sobrien		break;
2820236769Sobrien	    }
2821236769Sobrien	case '[':
2822236769Sobrien	    {
2823236769Sobrien		/*
2824236769Sobrien		 * Look for the closing ']', recursively
2825236769Sobrien		 * expanding any embedded variables.
2826236769Sobrien		 *
2827236769Sobrien		 * estr is a pointer to the expanded result,
2828236769Sobrien		 * which we must free().
2829236769Sobrien		 */
2830236769Sobrien		char *estr;
2831236769Sobrien
2832236769Sobrien		cp = tstr+1; /* point to char after '[' */
2833236769Sobrien		delim = ']'; /* look for closing ']' */
2834236769Sobrien		estr = VarGetPattern(ctxt, &parsestate,
2835236769Sobrien				     errnum, &cp, delim,
2836236769Sobrien				     NULL, NULL, NULL);
2837236769Sobrien		if (estr == NULL)
2838236769Sobrien		    goto cleanup; /* report missing ']' */
2839236769Sobrien		/* now cp points just after the closing ']' */
2840236769Sobrien		delim = '\0';
2841236769Sobrien		if (cp[0] != ':' && cp[0] != endc) {
2842236769Sobrien		    /* Found junk after ']' */
2843236769Sobrien		    free(estr);
2844236769Sobrien		    goto bad_modifier;
2845236769Sobrien		}
2846236769Sobrien		if (estr[0] == '\0') {
2847236769Sobrien		    /* Found empty square brackets in ":[]". */
2848236769Sobrien		    free(estr);
2849236769Sobrien		    goto bad_modifier;
2850236769Sobrien		} else if (estr[0] == '#' && estr[1] == '\0') {
2851236769Sobrien		    /* Found ":[#]" */
2852236769Sobrien
2853236769Sobrien		    /*
2854236769Sobrien		     * We will need enough space for the decimal
2855236769Sobrien		     * representation of an int.  We calculate the
2856236769Sobrien		     * space needed for the octal representation,
2857236769Sobrien		     * and add enough slop to cope with a '-' sign
2858236769Sobrien		     * (which should never be needed) and a '\0'
2859236769Sobrien		     * string terminator.
2860236769Sobrien		     */
2861236769Sobrien		    int newStrSize =
2862236769Sobrien			(sizeof(int) * CHAR_BIT + 2) / 3 + 2;
2863236769Sobrien
2864236769Sobrien		    newStr = bmake_malloc(newStrSize);
2865236769Sobrien		    if (parsestate.oneBigWord) {
2866236769Sobrien			strncpy(newStr, "1", newStrSize);
2867236769Sobrien		    } else {
2868236769Sobrien			/* XXX: brk_string() is a rather expensive
2869236769Sobrien			 * way of counting words. */
2870236769Sobrien			char **av;
2871236769Sobrien			char *as;
2872236769Sobrien			int ac;
2873236769Sobrien
2874236769Sobrien			av = brk_string(nstr, &ac, FALSE, &as);
2875236769Sobrien			snprintf(newStr, newStrSize,  "%d", ac);
2876236769Sobrien			free(as);
2877236769Sobrien			free(av);
2878236769Sobrien		    }
2879236769Sobrien		    termc = *cp;
2880236769Sobrien		    free(estr);
2881236769Sobrien		    break;
2882236769Sobrien		} else if (estr[0] == '*' && estr[1] == '\0') {
2883236769Sobrien		    /* Found ":[*]" */
2884236769Sobrien		    parsestate.oneBigWord = TRUE;
2885236769Sobrien		    newStr = nstr;
2886236769Sobrien		    termc = *cp;
2887236769Sobrien		    free(estr);
2888236769Sobrien		    break;
2889236769Sobrien		} else if (estr[0] == '@' && estr[1] == '\0') {
2890236769Sobrien		    /* Found ":[@]" */
2891236769Sobrien		    parsestate.oneBigWord = FALSE;
2892236769Sobrien		    newStr = nstr;
2893236769Sobrien		    termc = *cp;
2894236769Sobrien		    free(estr);
2895236769Sobrien		    break;
2896236769Sobrien		} else {
2897236769Sobrien		    /*
2898236769Sobrien		     * We expect estr to contain a single
2899236769Sobrien		     * integer for :[N], or two integers
2900236769Sobrien		     * separated by ".." for :[start..end].
2901236769Sobrien		     */
2902236769Sobrien		    char *ep;
2903236769Sobrien
2904236769Sobrien		    VarSelectWords_t seldata = { 0, 0 };
2905236769Sobrien
2906236769Sobrien		    seldata.start = strtol(estr, &ep, 0);
2907236769Sobrien		    if (ep == estr) {
2908236769Sobrien			/* Found junk instead of a number */
2909236769Sobrien			free(estr);
2910236769Sobrien			goto bad_modifier;
2911236769Sobrien		    } else if (ep[0] == '\0') {
2912236769Sobrien			/* Found only one integer in :[N] */
2913236769Sobrien			seldata.end = seldata.start;
2914236769Sobrien		    } else if (ep[0] == '.' && ep[1] == '.' &&
2915236769Sobrien			       ep[2] != '\0') {
2916236769Sobrien			/* Expecting another integer after ".." */
2917236769Sobrien			ep += 2;
2918236769Sobrien			seldata.end = strtol(ep, &ep, 0);
2919236769Sobrien			if (ep[0] != '\0') {
2920236769Sobrien			    /* Found junk after ".." */
2921236769Sobrien			    free(estr);
2922236769Sobrien			    goto bad_modifier;
2923236769Sobrien			}
2924236769Sobrien		    } else {
2925236769Sobrien			/* Found junk instead of ".." */
2926236769Sobrien			free(estr);
2927236769Sobrien			goto bad_modifier;
2928236769Sobrien		    }
2929236769Sobrien		    /*
2930236769Sobrien		     * Now seldata is properly filled in,
2931236769Sobrien		     * but we still have to check for 0 as
2932236769Sobrien		     * a special case.
2933236769Sobrien		     */
2934236769Sobrien		    if (seldata.start == 0 && seldata.end == 0) {
2935236769Sobrien			/* ":[0]" or perhaps ":[0..0]" */
2936236769Sobrien			parsestate.oneBigWord = TRUE;
2937236769Sobrien			newStr = nstr;
2938236769Sobrien			termc = *cp;
2939236769Sobrien			free(estr);
2940236769Sobrien			break;
2941236769Sobrien		    } else if (seldata.start == 0 ||
2942236769Sobrien			       seldata.end == 0) {
2943236769Sobrien			/* ":[0..N]" or ":[N..0]" */
2944236769Sobrien			free(estr);
2945236769Sobrien			goto bad_modifier;
2946236769Sobrien		    }
2947236769Sobrien		    /*
2948236769Sobrien		     * Normal case: select the words
2949236769Sobrien		     * described by seldata.
2950236769Sobrien		     */
2951236769Sobrien		    newStr = VarSelectWords(ctxt, &parsestate,
2952236769Sobrien					    nstr, &seldata);
2953236769Sobrien
2954236769Sobrien		    termc = *cp;
2955236769Sobrien		    free(estr);
2956236769Sobrien		    break;
2957236769Sobrien		}
2958236769Sobrien
2959236769Sobrien	    }
2960236769Sobrien	case 'g':
2961236769Sobrien	    cp = tstr + 1;	/* make sure it is set */
2962236769Sobrien	    if (STRMOD_MATCH(tstr, "gmtime", 6)) {
2963236769Sobrien		newStr = VarStrftime(nstr, 1);
2964236769Sobrien		cp = tstr + 6;
2965236769Sobrien		termc = *cp;
2966236769Sobrien	    } else {
2967236769Sobrien		goto default_case;
2968236769Sobrien	    }
2969236769Sobrien	    break;
2970236769Sobrien	case 'h':
2971236769Sobrien	    cp = tstr + 1;	/* make sure it is set */
2972236769Sobrien	    if (STRMOD_MATCH(tstr, "hash", 4)) {
2973236769Sobrien		newStr = VarHash(nstr);
2974236769Sobrien		cp = tstr + 4;
2975236769Sobrien		termc = *cp;
2976236769Sobrien	    } else {
2977236769Sobrien		goto default_case;
2978236769Sobrien	    }
2979236769Sobrien	    break;
2980236769Sobrien	case 'l':
2981236769Sobrien	    cp = tstr + 1;	/* make sure it is set */
2982236769Sobrien	    if (STRMOD_MATCH(tstr, "localtime", 9)) {
2983236769Sobrien		newStr = VarStrftime(nstr, 0);
2984236769Sobrien		cp = tstr + 9;
2985236769Sobrien		termc = *cp;
2986236769Sobrien	    } else {
2987236769Sobrien		goto default_case;
2988236769Sobrien	    }
2989236769Sobrien	    break;
2990236769Sobrien	case 't':
2991236769Sobrien	    {
2992236769Sobrien		cp = tstr + 1;	/* make sure it is set */
2993236769Sobrien		if (tstr[1] != endc && tstr[1] != ':') {
2994236769Sobrien		    if (tstr[1] == 's') {
2995236769Sobrien			/*
2996236769Sobrien			 * Use the char (if any) at tstr[2]
2997236769Sobrien			 * as the word separator.
2998236769Sobrien			 */
2999236769Sobrien			VarPattern pattern;
3000236769Sobrien
3001236769Sobrien			if (tstr[2] != endc &&
3002236769Sobrien			    (tstr[3] == endc || tstr[3] == ':')) {
3003236769Sobrien			    /* ":ts<unrecognised><endc>" or
3004236769Sobrien			     * ":ts<unrecognised>:" */
3005236769Sobrien			    parsestate.varSpace = tstr[2];
3006236769Sobrien			    cp = tstr + 3;
3007236769Sobrien			} else if (tstr[2] == endc || tstr[2] == ':') {
3008236769Sobrien			    /* ":ts<endc>" or ":ts:" */
3009236769Sobrien			    parsestate.varSpace = 0; /* no separator */
3010236769Sobrien			    cp = tstr + 2;
3011236769Sobrien			} else if (tstr[2] == '\\') {
3012236769Sobrien			    switch (tstr[3]) {
3013236769Sobrien			    case 'n':
3014236769Sobrien				parsestate.varSpace = '\n';
3015236769Sobrien				cp = tstr + 4;
3016236769Sobrien				break;
3017236769Sobrien			    case 't':
3018236769Sobrien				parsestate.varSpace = '\t';
3019236769Sobrien				cp = tstr + 4;
3020236769Sobrien				break;
3021236769Sobrien			    default:
3022236769Sobrien				if (isdigit((unsigned char)tstr[3])) {
3023236769Sobrien				    char *ep;
3024236769Sobrien
3025236769Sobrien				    parsestate.varSpace =
3026236769Sobrien					strtoul(&tstr[3], &ep, 0);
3027236769Sobrien				    if (*ep != ':' && *ep != endc)
3028236769Sobrien					goto bad_modifier;
3029236769Sobrien				    cp = ep;
3030236769Sobrien				} else {
3031236769Sobrien				    /*
3032236769Sobrien				     * ":ts<backslash><unrecognised>".
3033236769Sobrien				     */
3034236769Sobrien				    goto bad_modifier;
3035236769Sobrien				}
3036236769Sobrien				break;
3037236769Sobrien			    }
3038236769Sobrien			} else {
3039236769Sobrien			    /*
3040236769Sobrien			     * Found ":ts<unrecognised><unrecognised>".
3041236769Sobrien			     */
3042236769Sobrien			    goto bad_modifier;
3043236769Sobrien			}
3044236769Sobrien
3045236769Sobrien			termc = *cp;
3046236769Sobrien
3047236769Sobrien			/*
3048236769Sobrien			 * We cannot be certain that VarModify
3049236769Sobrien			 * will be used - even if there is a
3050236769Sobrien			 * subsequent modifier, so do a no-op
3051236769Sobrien			 * VarSubstitute now to for str to be
3052236769Sobrien			 * re-expanded without the spaces.
3053236769Sobrien			 */
3054236769Sobrien			pattern.flags = VAR_SUB_ONE;
3055236769Sobrien			pattern.lhs = pattern.rhs = "\032";
3056236769Sobrien			pattern.leftLen = pattern.rightLen = 1;
3057236769Sobrien
3058236769Sobrien			newStr = VarModify(ctxt, &parsestate, nstr,
3059236769Sobrien					   VarSubstitute,
3060236769Sobrien					   &pattern);
3061236769Sobrien		    } else if (tstr[2] == endc || tstr[2] == ':') {
3062236769Sobrien			/*
3063236769Sobrien			 * Check for two-character options:
3064236769Sobrien			 * ":tu", ":tl"
3065236769Sobrien			 */
3066236769Sobrien			if (tstr[1] == 'A') { /* absolute path */
3067236769Sobrien			    newStr = VarModify(ctxt, &parsestate, nstr,
3068236769Sobrien					       VarRealpath, NULL);
3069236769Sobrien			    cp = tstr + 2;
3070236769Sobrien			    termc = *cp;
3071249033Ssjg			} else if (tstr[1] == 'u') {
3072249033Ssjg			    char *dp = bmake_strdup(nstr);
3073249033Ssjg			    for (newStr = dp; *dp; dp++)
3074249033Ssjg				*dp = toupper((unsigned char)*dp);
3075236769Sobrien			    cp = tstr + 2;
3076236769Sobrien			    termc = *cp;
3077249033Ssjg			} else if (tstr[1] == 'l') {
3078249033Ssjg			    char *dp = bmake_strdup(nstr);
3079249033Ssjg			    for (newStr = dp; *dp; dp++)
3080249033Ssjg				*dp = tolower((unsigned char)*dp);
3081249033Ssjg			    cp = tstr + 2;
3082249033Ssjg			    termc = *cp;
3083236769Sobrien			} else if (tstr[1] == 'W' || tstr[1] == 'w') {
3084236769Sobrien			    parsestate.oneBigWord = (tstr[1] == 'W');
3085236769Sobrien			    newStr = nstr;
3086236769Sobrien			    cp = tstr + 2;
3087236769Sobrien			    termc = *cp;
3088236769Sobrien			} else {
3089236769Sobrien			    /* Found ":t<unrecognised>:" or
3090236769Sobrien			     * ":t<unrecognised><endc>". */
3091236769Sobrien			    goto bad_modifier;
3092236769Sobrien			}
3093236769Sobrien		    } else {
3094236769Sobrien			/*
3095236769Sobrien			 * Found ":t<unrecognised><unrecognised>".
3096236769Sobrien			 */
3097236769Sobrien			goto bad_modifier;
3098236769Sobrien		    }
3099236769Sobrien		} else {
3100236769Sobrien		    /*
3101236769Sobrien		     * Found ":t<endc>" or ":t:".
3102236769Sobrien		     */
3103236769Sobrien		    goto bad_modifier;
3104236769Sobrien		}
3105236769Sobrien		break;
3106236769Sobrien	    }
3107236769Sobrien	case 'N':
3108236769Sobrien	case 'M':
3109236769Sobrien	    {
3110236769Sobrien		char    *pattern;
3111236769Sobrien		const char *endpat; /* points just after end of pattern */
3112236769Sobrien		char    *cp2;
3113236769Sobrien		Boolean copy;	/* pattern should be, or has been, copied */
3114236769Sobrien		Boolean needSubst;
3115236769Sobrien		int nest;
3116236769Sobrien
3117236769Sobrien		copy = FALSE;
3118236769Sobrien		needSubst = FALSE;
3119236769Sobrien		nest = 1;
3120236769Sobrien		/*
3121236769Sobrien		 * In the loop below, ignore ':' unless we are at
3122236769Sobrien		 * (or back to) the original brace level.
3123236769Sobrien		 * XXX This will likely not work right if $() and ${}
3124236769Sobrien		 * are intermixed.
3125236769Sobrien		 */
3126236769Sobrien		for (cp = tstr + 1;
3127236769Sobrien		     *cp != '\0' && !(*cp == ':' && nest == 1);
3128236769Sobrien		     cp++)
3129236769Sobrien		    {
3130236769Sobrien			if (*cp == '\\' &&
3131236769Sobrien			    (cp[1] == ':' ||
3132236769Sobrien			     cp[1] == endc || cp[1] == startc)) {
3133236769Sobrien			    if (!needSubst) {
3134236769Sobrien				copy = TRUE;
3135236769Sobrien			    }
3136236769Sobrien			    cp++;
3137236769Sobrien			    continue;
3138236769Sobrien			}
3139236769Sobrien			if (*cp == '$') {
3140236769Sobrien			    needSubst = TRUE;
3141236769Sobrien			}
3142236769Sobrien			if (*cp == '(' || *cp == '{')
3143236769Sobrien			    ++nest;
3144236769Sobrien			if (*cp == ')' || *cp == '}') {
3145236769Sobrien			    --nest;
3146236769Sobrien			    if (nest == 0)
3147236769Sobrien				break;
3148236769Sobrien			}
3149236769Sobrien		    }
3150236769Sobrien		termc = *cp;
3151236769Sobrien		endpat = cp;
3152236769Sobrien		if (copy) {
3153236769Sobrien		    /*
3154236769Sobrien		     * Need to compress the \:'s out of the pattern, so
3155236769Sobrien		     * allocate enough room to hold the uncompressed
3156236769Sobrien		     * pattern (note that cp started at tstr+1, so
3157236769Sobrien		     * cp - tstr takes the null byte into account) and
3158236769Sobrien		     * compress the pattern into the space.
3159236769Sobrien		     */
3160236769Sobrien		    pattern = bmake_malloc(cp - tstr);
3161236769Sobrien		    for (cp2 = pattern, cp = tstr + 1;
3162236769Sobrien			 cp < endpat;
3163236769Sobrien			 cp++, cp2++)
3164236769Sobrien			{
3165236769Sobrien			    if ((*cp == '\\') && (cp+1 < endpat) &&
3166236769Sobrien				(cp[1] == ':' || cp[1] == endc)) {
3167236769Sobrien				cp++;
3168236769Sobrien			    }
3169236769Sobrien			    *cp2 = *cp;
3170236769Sobrien			}
3171236769Sobrien		    *cp2 = '\0';
3172236769Sobrien		    endpat = cp2;
3173236769Sobrien		} else {
3174236769Sobrien		    /*
3175236769Sobrien		     * Either Var_Subst or VarModify will need a
3176236769Sobrien		     * nul-terminated string soon, so construct one now.
3177236769Sobrien		     */
3178236769Sobrien		    pattern = bmake_strndup(tstr+1, endpat - (tstr + 1));
3179236769Sobrien		}
3180236769Sobrien		if (needSubst) {
3181236769Sobrien		    /*
3182236769Sobrien		     * pattern contains embedded '$', so use Var_Subst to
3183236769Sobrien		     * expand it.
3184236769Sobrien		     */
3185236769Sobrien		    cp2 = pattern;
3186236769Sobrien		    pattern = Var_Subst(NULL, cp2, ctxt, errnum);
3187236769Sobrien		    free(cp2);
3188236769Sobrien		}
3189236769Sobrien		if (DEBUG(VAR))
3190246223Ssjg		    fprintf(debug_file, "Pattern[%s] for [%s] is [%s]\n",
3191246223Ssjg			v->name, nstr, pattern);
3192236769Sobrien		if (*tstr == 'M') {
3193236769Sobrien		    newStr = VarModify(ctxt, &parsestate, nstr, VarMatch,
3194236769Sobrien				       pattern);
3195236769Sobrien		} else {
3196236769Sobrien		    newStr = VarModify(ctxt, &parsestate, nstr, VarNoMatch,
3197236769Sobrien				       pattern);
3198236769Sobrien		}
3199236769Sobrien		free(pattern);
3200236769Sobrien		break;
3201236769Sobrien	    }
3202236769Sobrien	case 'S':
3203236769Sobrien	    {
3204236769Sobrien		VarPattern 	    pattern;
3205236769Sobrien		Var_Parse_State tmpparsestate;
3206236769Sobrien
3207236769Sobrien		pattern.flags = 0;
3208236769Sobrien		tmpparsestate = parsestate;
3209236769Sobrien		delim = tstr[1];
3210236769Sobrien		tstr += 2;
3211236769Sobrien
3212236769Sobrien		/*
3213236769Sobrien		 * If pattern begins with '^', it is anchored to the
3214236769Sobrien		 * start of the word -- skip over it and flag pattern.
3215236769Sobrien		 */
3216236769Sobrien		if (*tstr == '^') {
3217236769Sobrien		    pattern.flags |= VAR_MATCH_START;
3218236769Sobrien		    tstr += 1;
3219236769Sobrien		}
3220236769Sobrien
3221236769Sobrien		cp = tstr;
3222236769Sobrien		if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3223236769Sobrien						 &cp, delim,
3224236769Sobrien						 &pattern.flags,
3225236769Sobrien						 &pattern.leftLen,
3226236769Sobrien						 NULL)) == NULL)
3227236769Sobrien		    goto cleanup;
3228236769Sobrien
3229236769Sobrien		if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3230236769Sobrien						 &cp, delim, NULL,
3231236769Sobrien						 &pattern.rightLen,
3232236769Sobrien						 &pattern)) == NULL)
3233236769Sobrien		    goto cleanup;
3234236769Sobrien
3235236769Sobrien		/*
3236236769Sobrien		 * Check for global substitution. If 'g' after the final
3237236769Sobrien		 * delimiter, substitution is global and is marked that
3238236769Sobrien		 * way.
3239236769Sobrien		 */
3240236769Sobrien		for (;; cp++) {
3241236769Sobrien		    switch (*cp) {
3242236769Sobrien		    case 'g':
3243236769Sobrien			pattern.flags |= VAR_SUB_GLOBAL;
3244236769Sobrien			continue;
3245236769Sobrien		    case '1':
3246236769Sobrien			pattern.flags |= VAR_SUB_ONE;
3247236769Sobrien			continue;
3248236769Sobrien		    case 'W':
3249236769Sobrien			tmpparsestate.oneBigWord = TRUE;
3250236769Sobrien			continue;
3251236769Sobrien		    }
3252236769Sobrien		    break;
3253236769Sobrien		}
3254236769Sobrien
3255236769Sobrien		termc = *cp;
3256236769Sobrien		newStr = VarModify(ctxt, &tmpparsestate, nstr,
3257236769Sobrien				   VarSubstitute,
3258236769Sobrien				   &pattern);
3259236769Sobrien
3260236769Sobrien		/*
3261236769Sobrien		 * Free the two strings.
3262236769Sobrien		 */
3263236769Sobrien		free(UNCONST(pattern.lhs));
3264236769Sobrien		free(UNCONST(pattern.rhs));
3265236769Sobrien		delim = '\0';
3266236769Sobrien		break;
3267236769Sobrien	    }
3268236769Sobrien	case '?':
3269236769Sobrien	    {
3270236769Sobrien		VarPattern 	pattern;
3271236769Sobrien		Boolean	value;
3272236769Sobrien
3273236769Sobrien		/* find ':', and then substitute accordingly */
3274236769Sobrien
3275236769Sobrien		pattern.flags = 0;
3276236769Sobrien
3277236769Sobrien		cp = ++tstr;
3278236769Sobrien		delim = ':';
3279236769Sobrien		if ((pattern.lhs = VarGetPattern(ctxt, &parsestate, errnum,
3280236769Sobrien						 &cp, delim, NULL,
3281236769Sobrien						 &pattern.leftLen,
3282236769Sobrien						 NULL)) == NULL)
3283236769Sobrien		    goto cleanup;
3284236769Sobrien
3285236769Sobrien		/* BROPEN or PROPEN */
3286236769Sobrien		delim = endc;
3287236769Sobrien		if ((pattern.rhs = VarGetPattern(ctxt, &parsestate, errnum,
3288236769Sobrien						 &cp, delim, NULL,
3289236769Sobrien						 &pattern.rightLen,
3290236769Sobrien						 NULL)) == NULL)
3291236769Sobrien		    goto cleanup;
3292236769Sobrien
3293236769Sobrien		termc = *--cp;
3294236769Sobrien		delim = '\0';
3295236769Sobrien		if (Cond_EvalExpression(NULL, v->name, &value, 0)
3296236769Sobrien		    == COND_INVALID) {
3297236769Sobrien		    Error("Bad conditional expression `%s' in %s?%s:%s",
3298236769Sobrien			  v->name, v->name, pattern.lhs, pattern.rhs);
3299236769Sobrien		    goto cleanup;
3300236769Sobrien		}
3301236769Sobrien
3302236769Sobrien		if (value) {
3303236769Sobrien		    newStr = UNCONST(pattern.lhs);
3304236769Sobrien		    free(UNCONST(pattern.rhs));
3305236769Sobrien		} else {
3306236769Sobrien		    newStr = UNCONST(pattern.rhs);
3307236769Sobrien		    free(UNCONST(pattern.lhs));
3308236769Sobrien		}
3309236769Sobrien		if (v->flags & VAR_JUNK) {
3310236769Sobrien		    v->flags |= VAR_KEEP;
3311236769Sobrien		}
3312236769Sobrien		break;
3313236769Sobrien	    }
3314236769Sobrien#ifndef NO_REGEX
3315236769Sobrien	case 'C':
3316236769Sobrien	    {
3317236769Sobrien		VarREPattern    pattern;
3318236769Sobrien		char           *re;
3319236769Sobrien		int             error;
3320236769Sobrien		Var_Parse_State tmpparsestate;
3321236769Sobrien
3322236769Sobrien		pattern.flags = 0;
3323236769Sobrien		tmpparsestate = parsestate;
3324236769Sobrien		delim = tstr[1];
3325236769Sobrien		tstr += 2;
3326236769Sobrien
3327236769Sobrien		cp = tstr;
3328236769Sobrien
3329236769Sobrien		if ((re = VarGetPattern(ctxt, &parsestate, errnum, &cp, delim,
3330236769Sobrien					NULL, NULL, NULL)) == NULL)
3331236769Sobrien		    goto cleanup;
3332236769Sobrien
3333236769Sobrien		if ((pattern.replace = VarGetPattern(ctxt, &parsestate,
3334236769Sobrien						     errnum, &cp, delim, NULL,
3335236769Sobrien						     NULL, NULL)) == NULL){
3336236769Sobrien		    free(re);
3337236769Sobrien		    goto cleanup;
3338236769Sobrien		}
3339236769Sobrien
3340236769Sobrien		for (;; cp++) {
3341236769Sobrien		    switch (*cp) {
3342236769Sobrien		    case 'g':
3343236769Sobrien			pattern.flags |= VAR_SUB_GLOBAL;
3344236769Sobrien			continue;
3345236769Sobrien		    case '1':
3346236769Sobrien			pattern.flags |= VAR_SUB_ONE;
3347236769Sobrien			continue;
3348236769Sobrien		    case 'W':
3349236769Sobrien			tmpparsestate.oneBigWord = TRUE;
3350236769Sobrien			continue;
3351236769Sobrien		    }
3352236769Sobrien		    break;
3353236769Sobrien		}
3354236769Sobrien
3355236769Sobrien		termc = *cp;
3356236769Sobrien
3357236769Sobrien		error = regcomp(&pattern.re, re, REG_EXTENDED);
3358236769Sobrien		free(re);
3359236769Sobrien		if (error)  {
3360236769Sobrien		    *lengthPtr = cp - start + 1;
3361236769Sobrien		    VarREError(error, &pattern.re, "RE substitution error");
3362236769Sobrien		    free(pattern.replace);
3363236769Sobrien		    goto cleanup;
3364236769Sobrien		}
3365236769Sobrien
3366236769Sobrien		pattern.nsub = pattern.re.re_nsub + 1;
3367236769Sobrien		if (pattern.nsub < 1)
3368236769Sobrien		    pattern.nsub = 1;
3369236769Sobrien		if (pattern.nsub > 10)
3370236769Sobrien		    pattern.nsub = 10;
3371236769Sobrien		pattern.matches = bmake_malloc(pattern.nsub *
3372236769Sobrien					  sizeof(regmatch_t));
3373236769Sobrien		newStr = VarModify(ctxt, &tmpparsestate, nstr,
3374236769Sobrien				   VarRESubstitute,
3375236769Sobrien				   &pattern);
3376236769Sobrien		regfree(&pattern.re);
3377236769Sobrien		free(pattern.replace);
3378236769Sobrien		free(pattern.matches);
3379236769Sobrien		delim = '\0';
3380236769Sobrien		break;
3381236769Sobrien	    }
3382236769Sobrien#endif
3383236769Sobrien	case 'Q':
3384236769Sobrien	    if (tstr[1] == endc || tstr[1] == ':') {
3385236769Sobrien		newStr = VarQuote(nstr);
3386236769Sobrien		cp = tstr + 1;
3387236769Sobrien		termc = *cp;
3388236769Sobrien		break;
3389236769Sobrien	    }
3390236769Sobrien	    goto default_case;
3391236769Sobrien	case 'T':
3392236769Sobrien	    if (tstr[1] == endc || tstr[1] == ':') {
3393236769Sobrien		newStr = VarModify(ctxt, &parsestate, nstr, VarTail,
3394236769Sobrien				   NULL);
3395236769Sobrien		cp = tstr + 1;
3396236769Sobrien		termc = *cp;
3397236769Sobrien		break;
3398236769Sobrien	    }
3399236769Sobrien	    goto default_case;
3400236769Sobrien	case 'H':
3401236769Sobrien	    if (tstr[1] == endc || tstr[1] == ':') {
3402236769Sobrien		newStr = VarModify(ctxt, &parsestate, nstr, VarHead,
3403236769Sobrien				   NULL);
3404236769Sobrien		cp = tstr + 1;
3405236769Sobrien		termc = *cp;
3406236769Sobrien		break;
3407236769Sobrien	    }
3408236769Sobrien	    goto default_case;
3409236769Sobrien	case 'E':
3410236769Sobrien	    if (tstr[1] == endc || tstr[1] == ':') {
3411236769Sobrien		newStr = VarModify(ctxt, &parsestate, nstr, VarSuffix,
3412236769Sobrien				   NULL);
3413236769Sobrien		cp = tstr + 1;
3414236769Sobrien		termc = *cp;
3415236769Sobrien		break;
3416236769Sobrien	    }
3417236769Sobrien	    goto default_case;
3418236769Sobrien	case 'R':
3419236769Sobrien	    if (tstr[1] == endc || tstr[1] == ':') {
3420236769Sobrien		newStr = VarModify(ctxt, &parsestate, nstr, VarRoot,
3421236769Sobrien				   NULL);
3422236769Sobrien		cp = tstr + 1;
3423236769Sobrien		termc = *cp;
3424236769Sobrien		break;
3425236769Sobrien	    }
3426236769Sobrien	    goto default_case;
3427236769Sobrien	case 'O':
3428236769Sobrien	    {
3429236769Sobrien		char otype;
3430236769Sobrien
3431236769Sobrien		cp = tstr + 1;	/* skip to the rest in any case */
3432236769Sobrien		if (tstr[1] == endc || tstr[1] == ':') {
3433236769Sobrien		    otype = 's';
3434236769Sobrien		    termc = *cp;
3435236769Sobrien		} else if ( (tstr[1] == 'x') &&
3436236769Sobrien			    (tstr[2] == endc || tstr[2] == ':') ) {
3437236769Sobrien		    otype = tstr[1];
3438236769Sobrien		    cp = tstr + 2;
3439236769Sobrien		    termc = *cp;
3440236769Sobrien		} else {
3441236769Sobrien		    goto bad_modifier;
3442236769Sobrien		}
3443236769Sobrien		newStr = VarOrder(nstr, otype);
3444236769Sobrien		break;
3445236769Sobrien	    }
3446236769Sobrien	case 'u':
3447236769Sobrien	    if (tstr[1] == endc || tstr[1] == ':') {
3448236769Sobrien		newStr = VarUniq(nstr);
3449236769Sobrien		cp = tstr + 1;
3450236769Sobrien		termc = *cp;
3451236769Sobrien		break;
3452236769Sobrien	    }
3453236769Sobrien	    goto default_case;
3454236769Sobrien#ifdef SUNSHCMD
3455236769Sobrien	case 's':
3456236769Sobrien	    if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
3457236769Sobrien		const char *emsg;
3458236769Sobrien		newStr = Cmd_Exec(nstr, &emsg);
3459236769Sobrien		if (emsg)
3460236769Sobrien		    Error(emsg, nstr);
3461236769Sobrien		cp = tstr + 2;
3462236769Sobrien		termc = *cp;
3463236769Sobrien		break;
3464236769Sobrien	    }
3465236769Sobrien	    goto default_case;
3466236769Sobrien#endif
3467236769Sobrien	default:
3468236769Sobrien	default_case:
3469236769Sobrien	{
3470236769Sobrien#ifdef SYSVVARSUB
3471236769Sobrien	    /*
3472236769Sobrien	     * This can either be a bogus modifier or a System-V
3473236769Sobrien	     * substitution command.
3474236769Sobrien	     */
3475236769Sobrien	    VarPattern      pattern;
3476236769Sobrien	    Boolean         eqFound;
3477236769Sobrien
3478236769Sobrien	    pattern.flags = 0;
3479236769Sobrien	    eqFound = FALSE;
3480236769Sobrien	    /*
3481236769Sobrien	     * First we make a pass through the string trying
3482236769Sobrien	     * to verify it is a SYSV-make-style translation:
3483236769Sobrien	     * it must be: <string1>=<string2>)
3484236769Sobrien	     */
3485236769Sobrien	    cp = tstr;
3486236769Sobrien	    cnt = 1;
3487236769Sobrien	    while (*cp != '\0' && cnt) {
3488236769Sobrien		if (*cp == '=') {
3489236769Sobrien		    eqFound = TRUE;
3490236769Sobrien		    /* continue looking for endc */
3491236769Sobrien		}
3492236769Sobrien		else if (*cp == endc)
3493236769Sobrien		    cnt--;
3494236769Sobrien		else if (*cp == startc)
3495236769Sobrien		    cnt++;
3496236769Sobrien		if (cnt)
3497236769Sobrien		    cp++;
3498236769Sobrien	    }
3499236769Sobrien	    if (*cp == endc && eqFound) {
3500236769Sobrien
3501236769Sobrien		/*
3502236769Sobrien		 * Now we break this sucker into the lhs and
3503236769Sobrien		 * rhs. We must null terminate them of course.
3504236769Sobrien		 */
3505236769Sobrien		delim='=';
3506236769Sobrien		cp = tstr;
3507236769Sobrien		if ((pattern.lhs = VarGetPattern(ctxt, &parsestate,
3508236769Sobrien						 errnum, &cp, delim, &pattern.flags,
3509236769Sobrien						 &pattern.leftLen, NULL)) == NULL)
3510236769Sobrien		    goto cleanup;
3511236769Sobrien		delim = endc;
3512236769Sobrien		if ((pattern.rhs = VarGetPattern(ctxt, &parsestate,
3513236769Sobrien						 errnum, &cp, delim, NULL, &pattern.rightLen,
3514236769Sobrien						 &pattern)) == NULL)
3515236769Sobrien		    goto cleanup;
3516236769Sobrien
3517236769Sobrien		/*
3518236769Sobrien		 * SYSV modifications happen through the whole
3519236769Sobrien		 * string. Note the pattern is anchored at the end.
3520236769Sobrien		 */
3521236769Sobrien		termc = *--cp;
3522236769Sobrien		delim = '\0';
3523236769Sobrien		if (pattern.leftLen == 0 && *nstr == '\0') {
3524236769Sobrien		    newStr = nstr;	/* special case */
3525236769Sobrien		} else {
3526236769Sobrien		    newStr = VarModify(ctxt, &parsestate, nstr,
3527236769Sobrien				       VarSYSVMatch,
3528236769Sobrien				       &pattern);
3529236769Sobrien		}
3530236769Sobrien		free(UNCONST(pattern.lhs));
3531236769Sobrien		free(UNCONST(pattern.rhs));
3532236769Sobrien	    } else
3533236769Sobrien#endif
3534236769Sobrien		{
3535236769Sobrien		    Error("Unknown modifier '%c'", *tstr);
3536236769Sobrien		    for (cp = tstr+1;
3537236769Sobrien			 *cp != ':' && *cp != endc && *cp != '\0';
3538236769Sobrien			 cp++)
3539236769Sobrien			continue;
3540236769Sobrien		    termc = *cp;
3541236769Sobrien		    newStr = var_Error;
3542236769Sobrien		}
3543236769Sobrien	    }
3544236769Sobrien	}
3545236769Sobrien	if (DEBUG(VAR)) {
3546246223Ssjg	    fprintf(debug_file, "Result[%s] of :%c is \"%s\"\n",
3547246223Ssjg		v->name, modifier, newStr);
3548236769Sobrien	}
3549236769Sobrien
3550236769Sobrien	if (newStr != nstr) {
3551236769Sobrien	    if (*freePtr) {
3552236769Sobrien		free(nstr);
3553236769Sobrien		*freePtr = NULL;
3554236769Sobrien	    }
3555236769Sobrien	    nstr = newStr;
3556236769Sobrien	    if (nstr != var_Error && nstr != varNoError) {
3557236769Sobrien		*freePtr = nstr;
3558236769Sobrien	    }
3559236769Sobrien	}
3560236769Sobrien	if (termc == '\0' && endc != '\0') {
3561236769Sobrien	    Error("Unclosed variable specification (expecting '%c') for \"%s\" (value \"%s\") modifier %c", endc, v->name, nstr, modifier);
3562236769Sobrien	} else if (termc == ':') {
3563236769Sobrien	    cp++;
3564236769Sobrien	}
3565236769Sobrien	tstr = cp;
3566236769Sobrien    }
3567236769Sobrien out:
3568236769Sobrien    *lengthPtr = tstr - start;
3569236769Sobrien    return (nstr);
3570236769Sobrien
3571236769Sobrien bad_modifier:
3572236769Sobrien    /* "{(" */
3573236769Sobrien    Error("Bad modifier `:%.*s' for %s", (int)strcspn(tstr, ":)}"), tstr,
3574236769Sobrien	  v->name);
3575236769Sobrien
3576236769Sobrien cleanup:
3577236769Sobrien    *lengthPtr = cp - start;
3578236769Sobrien    if (delim != '\0')
3579236769Sobrien	Error("Unclosed substitution for %s (%c missing)",
3580236769Sobrien	      v->name, delim);
3581236769Sobrien    if (*freePtr) {
3582236769Sobrien	free(*freePtr);
3583236769Sobrien	*freePtr = NULL;
3584236769Sobrien    }
3585236769Sobrien    return (var_Error);
3586236769Sobrien}
3587236769Sobrien
3588236769Sobrien/*-
3589236769Sobrien *-----------------------------------------------------------------------
3590236769Sobrien * Var_Parse --
3591236769Sobrien *	Given the start of a variable invocation, extract the variable
3592236769Sobrien *	name and find its value, then modify it according to the
3593236769Sobrien *	specification.
3594236769Sobrien *
3595236769Sobrien * Input:
3596236769Sobrien *	str		The string to parse
3597236769Sobrien *	ctxt		The context for the variable
3598236769Sobrien *	errnum		TRUE if undefined variables are an error
3599236769Sobrien *	lengthPtr	OUT: The length of the specification
3600236769Sobrien *	freePtr		OUT: Non-NULL if caller should free *freePtr
3601236769Sobrien *
3602236769Sobrien * Results:
3603236769Sobrien *	The (possibly-modified) value of the variable or var_Error if the
3604236769Sobrien *	specification is invalid. The length of the specification is
3605236769Sobrien *	placed in *lengthPtr (for invalid specifications, this is just
3606236769Sobrien *	2...?).
3607236769Sobrien *	If *freePtr is non-NULL then it's a pointer that the caller
3608236769Sobrien *	should pass to free() to free memory used by the result.
3609236769Sobrien *
3610236769Sobrien * Side Effects:
3611236769Sobrien *	None.
3612236769Sobrien *
3613236769Sobrien *-----------------------------------------------------------------------
3614236769Sobrien */
3615236769Sobrien/* coverity[+alloc : arg-*4] */
3616236769Sobrienchar *
3617236769SobrienVar_Parse(const char *str, GNode *ctxt, Boolean errnum, int *lengthPtr,
3618236769Sobrien	  void **freePtr)
3619236769Sobrien{
3620236769Sobrien    const char	   *tstr;    	/* Pointer into str */
3621236769Sobrien    Var		   *v;		/* Variable in invocation */
3622236769Sobrien    Boolean 	    haveModifier;/* TRUE if have modifiers for the variable */
3623236769Sobrien    char	    endc;    	/* Ending character when variable in parens
3624236769Sobrien				 * or braces */
3625236769Sobrien    char	    startc;	/* Starting character when variable in parens
3626236769Sobrien				 * or braces */
3627236769Sobrien    int		    vlen;	/* Length of variable name */
3628236769Sobrien    const char 	   *start;	/* Points to original start of str */
3629236769Sobrien    char	   *nstr;	/* New string, used during expansion */
3630236769Sobrien    Boolean 	    dynamic;	/* TRUE if the variable is local and we're
3631236769Sobrien				 * expanding it in a non-local context. This
3632236769Sobrien				 * is done to support dynamic sources. The
3633236769Sobrien				 * result is just the invocation, unaltered */
3634236769Sobrien    Var_Parse_State parsestate; /* Flags passed to helper functions */
3635236769Sobrien    char	  name[2];
3636236769Sobrien
3637236769Sobrien    *freePtr = NULL;
3638236769Sobrien    dynamic = FALSE;
3639236769Sobrien    start = str;
3640236769Sobrien    parsestate.oneBigWord = FALSE;
3641236769Sobrien    parsestate.varSpace = ' ';	/* word separator */
3642236769Sobrien
3643236769Sobrien    startc = str[1];
3644236769Sobrien    if (startc != PROPEN && startc != BROPEN) {
3645236769Sobrien	/*
3646236769Sobrien	 * If it's not bounded by braces of some sort, life is much simpler.
3647236769Sobrien	 * We just need to check for the first character and return the
3648236769Sobrien	 * value if it exists.
3649236769Sobrien	 */
3650236769Sobrien
3651236769Sobrien	/* Error out some really stupid names */
3652236769Sobrien	if (startc == '\0' || strchr(")}:$", startc)) {
3653236769Sobrien	    *lengthPtr = 1;
3654236769Sobrien	    return var_Error;
3655236769Sobrien	}
3656236769Sobrien	name[0] = startc;
3657236769Sobrien	name[1] = '\0';
3658236769Sobrien
3659236769Sobrien	v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3660236769Sobrien	if (v == NULL) {
3661236769Sobrien	    *lengthPtr = 2;
3662236769Sobrien
3663236769Sobrien	    if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
3664236769Sobrien		/*
3665236769Sobrien		 * If substituting a local variable in a non-local context,
3666236769Sobrien		 * assume it's for dynamic source stuff. We have to handle
3667236769Sobrien		 * this specially and return the longhand for the variable
3668236769Sobrien		 * with the dollar sign escaped so it makes it back to the
3669236769Sobrien		 * caller. Only four of the local variables are treated
3670236769Sobrien		 * specially as they are the only four that will be set
3671236769Sobrien		 * when dynamic sources are expanded.
3672236769Sobrien		 */
3673236769Sobrien		switch (str[1]) {
3674236769Sobrien		    case '@':
3675236769Sobrien			return UNCONST("$(.TARGET)");
3676236769Sobrien		    case '%':
3677236769Sobrien			return UNCONST("$(.ARCHIVE)");
3678236769Sobrien		    case '*':
3679236769Sobrien			return UNCONST("$(.PREFIX)");
3680236769Sobrien		    case '!':
3681236769Sobrien			return UNCONST("$(.MEMBER)");
3682236769Sobrien		}
3683236769Sobrien	    }
3684236769Sobrien	    /*
3685236769Sobrien	     * Error
3686236769Sobrien	     */
3687236769Sobrien	    return (errnum ? var_Error : varNoError);
3688236769Sobrien	} else {
3689236769Sobrien	    haveModifier = FALSE;
3690236769Sobrien	    tstr = &str[1];
3691236769Sobrien	    endc = str[1];
3692236769Sobrien	}
3693236769Sobrien    } else {
3694236769Sobrien	Buffer buf;	/* Holds the variable name */
3695236769Sobrien
3696236769Sobrien	endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
3697236769Sobrien	Buf_Init(&buf, 0);
3698236769Sobrien
3699236769Sobrien	/*
3700236769Sobrien	 * Skip to the end character or a colon, whichever comes first.
3701236769Sobrien	 */
3702236769Sobrien	for (tstr = str + 2;
3703236769Sobrien	     *tstr != '\0' && *tstr != endc && *tstr != ':';
3704236769Sobrien	     tstr++)
3705236769Sobrien	{
3706236769Sobrien	    /*
3707236769Sobrien	     * A variable inside a variable, expand
3708236769Sobrien	     */
3709236769Sobrien	    if (*tstr == '$') {
3710236769Sobrien		int rlen;
3711236769Sobrien		void *freeIt;
3712236769Sobrien		char *rval = Var_Parse(tstr, ctxt, errnum, &rlen, &freeIt);
3713236769Sobrien		if (rval != NULL) {
3714236769Sobrien		    Buf_AddBytes(&buf, strlen(rval), rval);
3715236769Sobrien		}
3716236769Sobrien		if (freeIt)
3717236769Sobrien		    free(freeIt);
3718236769Sobrien		tstr += rlen - 1;
3719236769Sobrien	    }
3720236769Sobrien	    else
3721236769Sobrien		Buf_AddByte(&buf, *tstr);
3722236769Sobrien	}
3723236769Sobrien	if (*tstr == ':') {
3724236769Sobrien	    haveModifier = TRUE;
3725236769Sobrien	} else if (*tstr != '\0') {
3726236769Sobrien	    haveModifier = FALSE;
3727236769Sobrien	} else {
3728236769Sobrien	    /*
3729236769Sobrien	     * If we never did find the end character, return NULL
3730236769Sobrien	     * right now, setting the length to be the distance to
3731236769Sobrien	     * the end of the string, since that's what make does.
3732236769Sobrien	     */
3733236769Sobrien	    *lengthPtr = tstr - str;
3734236769Sobrien	    Buf_Destroy(&buf, TRUE);
3735236769Sobrien	    return (var_Error);
3736236769Sobrien	}
3737236769Sobrien	str = Buf_GetAll(&buf, &vlen);
3738236769Sobrien
3739236769Sobrien	/*
3740236769Sobrien	 * At this point, str points into newly allocated memory from
3741236769Sobrien	 * buf, containing only the name of the variable.
3742236769Sobrien	 *
3743236769Sobrien	 * start and tstr point into the const string that was pointed
3744236769Sobrien	 * to by the original value of the str parameter.  start points
3745236769Sobrien	 * to the '$' at the beginning of the string, while tstr points
3746236769Sobrien	 * to the char just after the end of the variable name -- this
3747236769Sobrien	 * will be '\0', ':', PRCLOSE, or BRCLOSE.
3748236769Sobrien	 */
3749236769Sobrien
3750236769Sobrien	v = VarFind(str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
3751236769Sobrien	/*
3752236769Sobrien	 * Check also for bogus D and F forms of local variables since we're
3753236769Sobrien	 * in a local context and the name is the right length.
3754236769Sobrien	 */
3755236769Sobrien	if ((v == NULL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
3756236769Sobrien		(vlen == 2) && (str[1] == 'F' || str[1] == 'D') &&
3757236769Sobrien		strchr("@%*!<>", str[0]) != NULL) {
3758236769Sobrien	    /*
3759236769Sobrien	     * Well, it's local -- go look for it.
3760236769Sobrien	     */
3761236769Sobrien	    name[0] = *str;
3762236769Sobrien	    name[1] = '\0';
3763236769Sobrien	    v = VarFind(name, ctxt, 0);
3764236769Sobrien
3765236769Sobrien	    if (v != NULL) {
3766236769Sobrien		/*
3767236769Sobrien		 * No need for nested expansion or anything, as we're
3768236769Sobrien		 * the only one who sets these things and we sure don't
3769236769Sobrien		 * but nested invocations in them...
3770236769Sobrien		 */
3771236769Sobrien		nstr = Buf_GetAll(&v->val, NULL);
3772236769Sobrien
3773236769Sobrien		if (str[1] == 'D') {
3774236769Sobrien		    nstr = VarModify(ctxt, &parsestate, nstr, VarHead,
3775236769Sobrien				    NULL);
3776236769Sobrien		} else {
3777236769Sobrien		    nstr = VarModify(ctxt, &parsestate, nstr, VarTail,
3778236769Sobrien				    NULL);
3779236769Sobrien		}
3780236769Sobrien		/*
3781236769Sobrien		 * Resulting string is dynamically allocated, so
3782236769Sobrien		 * tell caller to free it.
3783236769Sobrien		 */
3784236769Sobrien		*freePtr = nstr;
3785236769Sobrien		*lengthPtr = tstr-start+1;
3786236769Sobrien		Buf_Destroy(&buf, TRUE);
3787236769Sobrien		VarFreeEnv(v, TRUE);
3788236769Sobrien		return nstr;
3789236769Sobrien	    }
3790236769Sobrien	}
3791236769Sobrien
3792236769Sobrien	if (v == NULL) {
3793236769Sobrien	    if (((vlen == 1) ||
3794236769Sobrien		 (((vlen == 2) && (str[1] == 'F' || str[1] == 'D')))) &&
3795236769Sobrien		((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3796236769Sobrien	    {
3797236769Sobrien		/*
3798236769Sobrien		 * If substituting a local variable in a non-local context,
3799236769Sobrien		 * assume it's for dynamic source stuff. We have to handle
3800236769Sobrien		 * this specially and return the longhand for the variable
3801236769Sobrien		 * with the dollar sign escaped so it makes it back to the
3802236769Sobrien		 * caller. Only four of the local variables are treated
3803236769Sobrien		 * specially as they are the only four that will be set
3804236769Sobrien		 * when dynamic sources are expanded.
3805236769Sobrien		 */
3806236769Sobrien		switch (*str) {
3807236769Sobrien		    case '@':
3808236769Sobrien		    case '%':
3809236769Sobrien		    case '*':
3810236769Sobrien		    case '!':
3811236769Sobrien			dynamic = TRUE;
3812236769Sobrien			break;
3813236769Sobrien		}
3814236769Sobrien	    } else if ((vlen > 2) && (*str == '.') &&
3815236769Sobrien		       isupper((unsigned char) str[1]) &&
3816236769Sobrien		       ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
3817236769Sobrien	    {
3818236769Sobrien		int	len;
3819236769Sobrien
3820236769Sobrien		len = vlen - 1;
3821236769Sobrien		if ((strncmp(str, ".TARGET", len) == 0) ||
3822236769Sobrien		    (strncmp(str, ".ARCHIVE", len) == 0) ||
3823236769Sobrien		    (strncmp(str, ".PREFIX", len) == 0) ||
3824236769Sobrien		    (strncmp(str, ".MEMBER", len) == 0))
3825236769Sobrien		{
3826236769Sobrien		    dynamic = TRUE;
3827236769Sobrien		}
3828236769Sobrien	    }
3829236769Sobrien
3830236769Sobrien	    if (!haveModifier) {
3831236769Sobrien		/*
3832236769Sobrien		 * No modifiers -- have specification length so we can return
3833236769Sobrien		 * now.
3834236769Sobrien		 */
3835236769Sobrien		*lengthPtr = tstr - start + 1;
3836236769Sobrien		if (dynamic) {
3837236769Sobrien		    char *pstr = bmake_strndup(start, *lengthPtr);
3838236769Sobrien		    *freePtr = pstr;
3839236769Sobrien		    Buf_Destroy(&buf, TRUE);
3840236769Sobrien		    return(pstr);
3841236769Sobrien		} else {
3842236769Sobrien		    Buf_Destroy(&buf, TRUE);
3843236769Sobrien		    return (errnum ? var_Error : varNoError);
3844236769Sobrien		}
3845236769Sobrien	    } else {
3846236769Sobrien		/*
3847236769Sobrien		 * Still need to get to the end of the variable specification,
3848236769Sobrien		 * so kludge up a Var structure for the modifications
3849236769Sobrien		 */
3850236769Sobrien		v = bmake_malloc(sizeof(Var));
3851236769Sobrien		v->name = UNCONST(str);
3852236769Sobrien		Buf_Init(&v->val, 1);
3853236769Sobrien		v->flags = VAR_JUNK;
3854236769Sobrien		Buf_Destroy(&buf, FALSE);
3855236769Sobrien	    }
3856236769Sobrien	} else
3857236769Sobrien	    Buf_Destroy(&buf, TRUE);
3858236769Sobrien    }
3859236769Sobrien
3860236769Sobrien    if (v->flags & VAR_IN_USE) {
3861236769Sobrien	Fatal("Variable %s is recursive.", v->name);
3862236769Sobrien	/*NOTREACHED*/
3863236769Sobrien    } else {
3864236769Sobrien	v->flags |= VAR_IN_USE;
3865236769Sobrien    }
3866236769Sobrien    /*
3867236769Sobrien     * Before doing any modification, we have to make sure the value
3868236769Sobrien     * has been fully expanded. If it looks like recursion might be
3869236769Sobrien     * necessary (there's a dollar sign somewhere in the variable's value)
3870236769Sobrien     * we just call Var_Subst to do any other substitutions that are
3871236769Sobrien     * necessary. Note that the value returned by Var_Subst will have
3872236769Sobrien     * been dynamically-allocated, so it will need freeing when we
3873236769Sobrien     * return.
3874236769Sobrien     */
3875236769Sobrien    nstr = Buf_GetAll(&v->val, NULL);
3876236769Sobrien    if (strchr(nstr, '$') != NULL) {
3877236769Sobrien	nstr = Var_Subst(NULL, nstr, ctxt, errnum);
3878236769Sobrien	*freePtr = nstr;
3879236769Sobrien    }
3880236769Sobrien
3881236769Sobrien    v->flags &= ~VAR_IN_USE;
3882236769Sobrien
3883236769Sobrien    if ((nstr != NULL) && haveModifier) {
3884236769Sobrien	int used;
3885236769Sobrien	/*
3886236769Sobrien	 * Skip initial colon.
3887236769Sobrien	 */
3888236769Sobrien	tstr++;
3889236769Sobrien
3890236769Sobrien	nstr = ApplyModifiers(nstr, tstr, startc, endc,
3891236769Sobrien			      v, ctxt, errnum, &used, freePtr);
3892236769Sobrien	tstr += used;
3893236769Sobrien    }
3894236769Sobrien    if (*tstr) {
3895236769Sobrien	*lengthPtr = tstr - start + 1;
3896236769Sobrien    } else {
3897236769Sobrien	*lengthPtr = tstr - start;
3898236769Sobrien    }
3899236769Sobrien
3900236769Sobrien    if (v->flags & VAR_FROM_ENV) {
3901236769Sobrien	Boolean	  destroy = FALSE;
3902236769Sobrien
3903236769Sobrien	if (nstr != Buf_GetAll(&v->val, NULL)) {
3904236769Sobrien	    destroy = TRUE;
3905236769Sobrien	} else {
3906236769Sobrien	    /*
3907236769Sobrien	     * Returning the value unmodified, so tell the caller to free
3908236769Sobrien	     * the thing.
3909236769Sobrien	     */
3910236769Sobrien	    *freePtr = nstr;
3911236769Sobrien	}
3912236769Sobrien	VarFreeEnv(v, destroy);
3913236769Sobrien    } else if (v->flags & VAR_JUNK) {
3914236769Sobrien	/*
3915236769Sobrien	 * Perform any free'ing needed and set *freePtr to NULL so the caller
3916236769Sobrien	 * doesn't try to free a static pointer.
3917236769Sobrien	 * If VAR_KEEP is also set then we want to keep str as is.
3918236769Sobrien	 */
3919236769Sobrien	if (!(v->flags & VAR_KEEP)) {
3920236769Sobrien	    if (*freePtr) {
3921236769Sobrien		free(nstr);
3922236769Sobrien		*freePtr = NULL;
3923236769Sobrien	    }
3924236769Sobrien	    if (dynamic) {
3925236769Sobrien		nstr = bmake_strndup(start, *lengthPtr);
3926236769Sobrien		*freePtr = nstr;
3927236769Sobrien	    } else {
3928236769Sobrien		nstr = errnum ? var_Error : varNoError;
3929236769Sobrien	    }
3930236769Sobrien	}
3931236769Sobrien	if (nstr != Buf_GetAll(&v->val, NULL))
3932236769Sobrien	    Buf_Destroy(&v->val, TRUE);
3933236769Sobrien	free(v->name);
3934236769Sobrien	free(v);
3935236769Sobrien    }
3936236769Sobrien    return (nstr);
3937236769Sobrien}
3938236769Sobrien
3939236769Sobrien/*-
3940236769Sobrien *-----------------------------------------------------------------------
3941236769Sobrien * Var_Subst  --
3942236769Sobrien *	Substitute for all variables in the given string in the given context
3943236769Sobrien *	If undefErr is TRUE, Parse_Error will be called when an undefined
3944236769Sobrien *	variable is encountered.
3945236769Sobrien *
3946236769Sobrien * Input:
3947236769Sobrien *	var		Named variable || NULL for all
3948236769Sobrien *	str		the string which to substitute
3949236769Sobrien *	ctxt		the context wherein to find variables
3950236769Sobrien *	undefErr	TRUE if undefineds are an error
3951236769Sobrien *
3952236769Sobrien * Results:
3953236769Sobrien *	The resulting string.
3954236769Sobrien *
3955236769Sobrien * Side Effects:
3956236769Sobrien *	None. The old string must be freed by the caller
3957236769Sobrien *-----------------------------------------------------------------------
3958236769Sobrien */
3959236769Sobrienchar *
3960236769SobrienVar_Subst(const char *var, const char *str, GNode *ctxt, Boolean undefErr)
3961236769Sobrien{
3962236769Sobrien    Buffer  	  buf;		    /* Buffer for forming things */
3963236769Sobrien    char    	  *val;		    /* Value to substitute for a variable */
3964236769Sobrien    int		  length;   	    /* Length of the variable invocation */
3965236769Sobrien    Boolean	  trailingBslash;   /* variable ends in \ */
3966236769Sobrien    void 	  *freeIt = NULL;    /* Set if it should be freed */
3967236769Sobrien    static Boolean errorReported;   /* Set true if an error has already
3968236769Sobrien				     * been reported to prevent a plethora
3969236769Sobrien				     * of messages when recursing */
3970236769Sobrien
3971236769Sobrien    Buf_Init(&buf, 0);
3972236769Sobrien    errorReported = FALSE;
3973236769Sobrien    trailingBslash = FALSE;
3974236769Sobrien
3975236769Sobrien    while (*str) {
3976236769Sobrien	if (*str == '\n' && trailingBslash)
3977236769Sobrien	    Buf_AddByte(&buf, ' ');
3978236769Sobrien	if (var == NULL && (*str == '$') && (str[1] == '$')) {
3979236769Sobrien	    /*
3980236769Sobrien	     * A dollar sign may be escaped either with another dollar sign.
3981236769Sobrien	     * In such a case, we skip over the escape character and store the
3982236769Sobrien	     * dollar sign into the buffer directly.
3983236769Sobrien	     */
3984236769Sobrien	    str++;
3985236769Sobrien	    Buf_AddByte(&buf, *str);
3986236769Sobrien	    str++;
3987236769Sobrien	} else if (*str != '$') {
3988236769Sobrien	    /*
3989236769Sobrien	     * Skip as many characters as possible -- either to the end of
3990236769Sobrien	     * the string or to the next dollar sign (variable invocation).
3991236769Sobrien	     */
3992236769Sobrien	    const char  *cp;
3993236769Sobrien
3994236769Sobrien	    for (cp = str++; *str != '$' && *str != '\0'; str++)
3995236769Sobrien		continue;
3996236769Sobrien	    Buf_AddBytes(&buf, str - cp, cp);
3997236769Sobrien	} else {
3998236769Sobrien	    if (var != NULL) {
3999236769Sobrien		int expand;
4000236769Sobrien		for (;;) {
4001236769Sobrien		    if (str[1] == '\0') {
4002236769Sobrien			/* A trailing $ is kind of a special case */
4003236769Sobrien			Buf_AddByte(&buf, str[0]);
4004236769Sobrien			str++;
4005236769Sobrien			expand = FALSE;
4006236769Sobrien		    } else if (str[1] != PROPEN && str[1] != BROPEN) {
4007236769Sobrien			if (str[1] != *var || strlen(var) > 1) {
4008236769Sobrien			    Buf_AddBytes(&buf, 2, str);
4009236769Sobrien			    str += 2;
4010236769Sobrien			    expand = FALSE;
4011236769Sobrien			}
4012236769Sobrien			else
4013236769Sobrien			    expand = TRUE;
4014236769Sobrien			break;
4015236769Sobrien		    }
4016236769Sobrien		    else {
4017236769Sobrien			const char *p;
4018236769Sobrien
4019236769Sobrien			/*
4020236769Sobrien			 * Scan up to the end of the variable name.
4021236769Sobrien			 */
4022236769Sobrien			for (p = &str[2]; *p &&
4023236769Sobrien			     *p != ':' && *p != PRCLOSE && *p != BRCLOSE; p++)
4024236769Sobrien			    if (*p == '$')
4025236769Sobrien				break;
4026236769Sobrien			/*
4027236769Sobrien			 * A variable inside the variable. We cannot expand
4028236769Sobrien			 * the external variable yet, so we try again with
4029236769Sobrien			 * the nested one
4030236769Sobrien			 */
4031236769Sobrien			if (*p == '$') {
4032236769Sobrien			    Buf_AddBytes(&buf, p - str, str);
4033236769Sobrien			    str = p;
4034236769Sobrien			    continue;
4035236769Sobrien			}
4036236769Sobrien
4037236769Sobrien			if (strncmp(var, str + 2, p - str - 2) != 0 ||
4038236769Sobrien			    var[p - str - 2] != '\0') {
4039236769Sobrien			    /*
4040236769Sobrien			     * Not the variable we want to expand, scan
4041236769Sobrien			     * until the next variable
4042236769Sobrien			     */
4043236769Sobrien			    for (;*p != '$' && *p != '\0'; p++)
4044236769Sobrien				continue;
4045236769Sobrien			    Buf_AddBytes(&buf, p - str, str);
4046236769Sobrien			    str = p;
4047236769Sobrien			    expand = FALSE;
4048236769Sobrien			}
4049236769Sobrien			else
4050236769Sobrien			    expand = TRUE;
4051236769Sobrien			break;
4052236769Sobrien		    }
4053236769Sobrien		}
4054236769Sobrien		if (!expand)
4055236769Sobrien		    continue;
4056236769Sobrien	    }
4057236769Sobrien
4058236769Sobrien	    val = Var_Parse(str, ctxt, undefErr, &length, &freeIt);
4059236769Sobrien
4060236769Sobrien	    /*
4061236769Sobrien	     * When we come down here, val should either point to the
4062236769Sobrien	     * value of this variable, suitably modified, or be NULL.
4063236769Sobrien	     * Length should be the total length of the potential
4064236769Sobrien	     * variable invocation (from $ to end character...)
4065236769Sobrien	     */
4066236769Sobrien	    if (val == var_Error || val == varNoError) {
4067236769Sobrien		/*
4068236769Sobrien		 * If performing old-time variable substitution, skip over
4069236769Sobrien		 * the variable and continue with the substitution. Otherwise,
4070236769Sobrien		 * store the dollar sign and advance str so we continue with
4071236769Sobrien		 * the string...
4072236769Sobrien		 */
4073236769Sobrien		if (oldVars) {
4074236769Sobrien		    str += length;
4075236769Sobrien		} else if (undefErr) {
4076236769Sobrien		    /*
4077236769Sobrien		     * If variable is undefined, complain and skip the
4078236769Sobrien		     * variable. The complaint will stop us from doing anything
4079236769Sobrien		     * when the file is parsed.
4080236769Sobrien		     */
4081236769Sobrien		    if (!errorReported) {
4082236769Sobrien			Parse_Error(PARSE_FATAL,
4083236769Sobrien				     "Undefined variable \"%.*s\"",length,str);
4084236769Sobrien		    }
4085236769Sobrien		    str += length;
4086236769Sobrien		    errorReported = TRUE;
4087236769Sobrien		} else {
4088236769Sobrien		    Buf_AddByte(&buf, *str);
4089236769Sobrien		    str += 1;
4090236769Sobrien		}
4091236769Sobrien	    } else {
4092236769Sobrien		/*
4093236769Sobrien		 * We've now got a variable structure to store in. But first,
4094236769Sobrien		 * advance the string pointer.
4095236769Sobrien		 */
4096236769Sobrien		str += length;
4097236769Sobrien
4098236769Sobrien		/*
4099236769Sobrien		 * Copy all the characters from the variable value straight
4100236769Sobrien		 * into the new string.
4101236769Sobrien		 */
4102236769Sobrien		length = strlen(val);
4103236769Sobrien		Buf_AddBytes(&buf, length, val);
4104236769Sobrien		trailingBslash = length > 0 && val[length - 1] == '\\';
4105236769Sobrien	    }
4106236769Sobrien	    if (freeIt) {
4107236769Sobrien		free(freeIt);
4108236769Sobrien		freeIt = NULL;
4109236769Sobrien	    }
4110236769Sobrien	}
4111236769Sobrien    }
4112236769Sobrien
4113236769Sobrien    return Buf_DestroyCompact(&buf);
4114236769Sobrien}
4115236769Sobrien
4116236769Sobrien/*-
4117236769Sobrien *-----------------------------------------------------------------------
4118236769Sobrien * Var_GetTail --
4119236769Sobrien *	Return the tail from each of a list of words. Used to set the
4120236769Sobrien *	System V local variables.
4121236769Sobrien *
4122236769Sobrien * Input:
4123236769Sobrien *	file		Filename to modify
4124236769Sobrien *
4125236769Sobrien * Results:
4126236769Sobrien *	The resulting string.
4127236769Sobrien *
4128236769Sobrien * Side Effects:
4129236769Sobrien *	None.
4130236769Sobrien *
4131236769Sobrien *-----------------------------------------------------------------------
4132236769Sobrien */
4133236769Sobrien#if 0
4134236769Sobrienchar *
4135236769SobrienVar_GetTail(char *file)
4136236769Sobrien{
4137236769Sobrien    return(VarModify(file, VarTail, NULL));
4138236769Sobrien}
4139236769Sobrien
4140236769Sobrien/*-
4141236769Sobrien *-----------------------------------------------------------------------
4142236769Sobrien * Var_GetHead --
4143236769Sobrien *	Find the leading components of a (list of) filename(s).
4144236769Sobrien *	XXX: VarHead does not replace foo by ., as (sun) System V make
4145236769Sobrien *	does.
4146236769Sobrien *
4147236769Sobrien * Input:
4148236769Sobrien *	file		Filename to manipulate
4149236769Sobrien *
4150236769Sobrien * Results:
4151236769Sobrien *	The leading components.
4152236769Sobrien *
4153236769Sobrien * Side Effects:
4154236769Sobrien *	None.
4155236769Sobrien *
4156236769Sobrien *-----------------------------------------------------------------------
4157236769Sobrien */
4158236769Sobrienchar *
4159236769SobrienVar_GetHead(char *file)
4160236769Sobrien{
4161236769Sobrien    return(VarModify(file, VarHead, NULL));
4162236769Sobrien}
4163236769Sobrien#endif
4164236769Sobrien
4165236769Sobrien/*-
4166236769Sobrien *-----------------------------------------------------------------------
4167236769Sobrien * Var_Init --
4168236769Sobrien *	Initialize the module
4169236769Sobrien *
4170236769Sobrien * Results:
4171236769Sobrien *	None
4172236769Sobrien *
4173236769Sobrien * Side Effects:
4174236769Sobrien *	The VAR_CMD and VAR_GLOBAL contexts are created
4175236769Sobrien *-----------------------------------------------------------------------
4176236769Sobrien */
4177236769Sobrienvoid
4178236769SobrienVar_Init(void)
4179236769Sobrien{
4180236769Sobrien    VAR_GLOBAL = Targ_NewGN("Global");
4181236769Sobrien    VAR_CMD = Targ_NewGN("Command");
4182236769Sobrien
4183236769Sobrien}
4184236769Sobrien
4185236769Sobrien
4186236769Sobrienvoid
4187236769SobrienVar_End(void)
4188236769Sobrien{
4189236769Sobrien}
4190236769Sobrien
4191236769Sobrien
4192236769Sobrien/****************** PRINT DEBUGGING INFO *****************/
4193236769Sobrienstatic void
4194236769SobrienVarPrintVar(void *vp)
4195236769Sobrien{
4196236769Sobrien    Var    *v = (Var *)vp;
4197236769Sobrien    fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
4198236769Sobrien}
4199236769Sobrien
4200236769Sobrien/*-
4201236769Sobrien *-----------------------------------------------------------------------
4202236769Sobrien * Var_Dump --
4203236769Sobrien *	print all variables in a context
4204236769Sobrien *-----------------------------------------------------------------------
4205236769Sobrien */
4206236769Sobrienvoid
4207236769SobrienVar_Dump(GNode *ctxt)
4208236769Sobrien{
4209236769Sobrien    Hash_Search search;
4210236769Sobrien    Hash_Entry *h;
4211236769Sobrien
4212236769Sobrien    for (h = Hash_EnumFirst(&ctxt->context, &search);
4213236769Sobrien	 h != NULL;
4214236769Sobrien	 h = Hash_EnumNext(&search)) {
4215236769Sobrien	    VarPrintVar(Hash_GetValue(h));
4216236769Sobrien    }
4217236769Sobrien}
4218