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