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