Home | History | Annotate | Line # | Download | only in make
var.c revision 1.60
      1 /*	$NetBSD: var.c,v 1.60 2001/06/01 20:33:38 sjg Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  * Copyright (c) 1989 by Berkeley Softworks
      7  * All rights reserved.
      8  *
      9  * This code is derived from software contributed to Berkeley by
     10  * Adam de Boor.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the University of
     23  *	California, Berkeley and its contributors.
     24  * 4. Neither the name of the University nor the names of its contributors
     25  *    may be used to endorse or promote products derived from this software
     26  *    without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     38  * SUCH DAMAGE.
     39  */
     40 
     41 #ifdef MAKE_BOOTSTRAP
     42 static char rcsid[] = "$NetBSD: var.c,v 1.60 2001/06/01 20:33:38 sjg Exp $";
     43 #else
     44 #include <sys/cdefs.h>
     45 #ifndef lint
     46 #if 0
     47 static char sccsid[] = "@(#)var.c	8.3 (Berkeley) 3/19/94";
     48 #else
     49 __RCSID("$NetBSD: var.c,v 1.60 2001/06/01 20:33:38 sjg Exp $");
     50 #endif
     51 #endif /* not lint */
     52 #endif
     53 
     54 /*-
     55  * var.c --
     56  *	Variable-handling functions
     57  *
     58  * Interface:
     59  *	Var_Set	  	    Set the value of a variable in the given
     60  *	    	  	    context. The variable is created if it doesn't
     61  *	    	  	    yet exist. The value and variable name need not
     62  *	    	  	    be preserved.
     63  *
     64  *	Var_Append	    Append more characters to an existing variable
     65  *	    	  	    in the given context. The variable needn't
     66  *	    	  	    exist already -- it will be created if it doesn't.
     67  *	    	  	    A space is placed between the old value and the
     68  *	    	  	    new one.
     69  *
     70  *	Var_Exists	    See if a variable exists.
     71  *
     72  *	Var_Value 	    Return the value of a variable in a context or
     73  *	    	  	    NULL if the variable is undefined.
     74  *
     75  *	Var_Subst 	    Substitute named variable, or all variables if
     76  *			    NULL in a string using
     77  *	    	  	    the given context as the top-most one. If the
     78  *	    	  	    third argument is non-zero, Parse_Error is
     79  *	    	  	    called if any variables are undefined.
     80  *
     81  *	Var_Parse 	    Parse a variable expansion from a string and
     82  *	    	  	    return the result and the number of characters
     83  *	    	  	    consumed.
     84  *
     85  *	Var_Delete	    Delete a variable in a context.
     86  *
     87  *	Var_Init  	    Initialize this module.
     88  *
     89  * Debugging:
     90  *	Var_Dump  	    Print out all variables defined in the given
     91  *	    	  	    context.
     92  *
     93  * XXX: There's a lot of duplication in these functions.
     94  */
     95 
     96 #include    <ctype.h>
     97 #ifndef NO_REGEX
     98 #include    <sys/types.h>
     99 #include    <regex.h>
    100 #endif
    101 #include    <stdlib.h>
    102 #include    "make.h"
    103 #include    "buf.h"
    104 
    105 /*
    106  * This is a harmless return value for Var_Parse that can be used by Var_Subst
    107  * to determine if there was an error in parsing -- easier than returning
    108  * a flag, as things outside this module don't give a hoot.
    109  */
    110 char 	var_Error[] = "";
    111 
    112 /*
    113  * Similar to var_Error, but returned when the 'err' flag for Var_Parse is
    114  * set false. Why not just use a constant? Well, gcc likes to condense
    115  * identical string instances...
    116  */
    117 static char	varNoError[] = "";
    118 
    119 /*
    120  * Internally, variables are contained in four different contexts.
    121  *	1) the environment. They may not be changed. If an environment
    122  *	    variable is appended-to, the result is placed in the global
    123  *	    context.
    124  *	2) the global context. Variables set in the Makefile are located in
    125  *	    the global context. It is the penultimate context searched when
    126  *	    substituting.
    127  *	3) the command-line context. All variables set on the command line
    128  *	   are placed in this context. They are UNALTERABLE once placed here.
    129  *	4) the local context. Each target has associated with it a context
    130  *	   list. On this list are located the structures describing such
    131  *	   local variables as $(@) and $(*)
    132  * The four contexts are searched in the reverse order from which they are
    133  * listed.
    134  */
    135 GNode          *VAR_GLOBAL;   /* variables from the makefile */
    136 GNode          *VAR_CMD;      /* variables defined on the command-line */
    137 
    138 #define FIND_CMD	0x1   /* look in VAR_CMD when searching */
    139 #define FIND_GLOBAL	0x2   /* look in VAR_GLOBAL as well */
    140 #define FIND_ENV  	0x4   /* look in the environment also */
    141 
    142 typedef struct Var {
    143     char          *name;	/* the variable's name */
    144     Buffer	  val;	    	/* its value */
    145     int	    	  flags;    	/* miscellaneous status flags */
    146 #define VAR_IN_USE	1   	    /* Variable's value currently being used.
    147 				     * Used to avoid recursion */
    148 #define VAR_FROM_ENV	2   	    /* Variable comes from the environment */
    149 #define VAR_JUNK  	4   	    /* Variable is a junk variable that
    150 				     * should be destroyed when done with
    151 				     * it. Used by Var_Parse for undefined,
    152 				     * modified variables */
    153 #define VAR_KEEP	8	    /* Variable is VAR_JUNK, but we found
    154 				     * a use for it in some modifier and
    155 				     * the value is therefore valid */
    156 }  Var;
    157 
    158 
    159 /* Var*Pattern flags */
    160 #define VAR_SUB_GLOBAL	0x01	/* Apply substitution globally */
    161 #define VAR_SUB_ONE	0x02	/* Apply substitution to one word */
    162 #define VAR_SUB_MATCHED	0x04	/* There was a match */
    163 #define VAR_MATCH_START	0x08	/* Match at start of word */
    164 #define VAR_MATCH_END	0x10	/* Match at end of word */
    165 #define VAR_NOSUBST	0x20	/* don't expand vars in VarGetPattern */
    166 
    167 typedef struct {
    168     char    	  *lhs;	    /* String to match */
    169     int	    	   leftLen; /* Length of string */
    170     char    	  *rhs;	    /* Replacement string (w/ &'s removed) */
    171     int	    	  rightLen; /* Length of replacement */
    172     int	    	  flags;
    173 } VarPattern;
    174 
    175 typedef struct {
    176     GNode	*ctxt;		/* variable context */
    177     char	*tvar;		/* name of temp var */
    178     int		tvarLen;
    179     char	*str;		/* string to expand */
    180     int		strLen;
    181     int		err;		/* err for not defined */
    182 } VarLoop_t;
    183 
    184 #ifndef NO_REGEX
    185 typedef struct {
    186     regex_t	   re;
    187     int		   nsub;
    188     regmatch_t 	  *matches;
    189     char 	  *replace;
    190     int		   flags;
    191 } VarREPattern;
    192 #endif
    193 
    194 static Var *VarFind __P((char *, GNode *, int));
    195 static void VarAdd __P((char *, char *, GNode *));
    196 static Boolean VarHead __P((char *, Boolean, Buffer, ClientData));
    197 static Boolean VarTail __P((char *, Boolean, Buffer, ClientData));
    198 static Boolean VarSuffix __P((char *, Boolean, Buffer, ClientData));
    199 static Boolean VarRoot __P((char *, Boolean, Buffer, ClientData));
    200 static Boolean VarMatch __P((char *, Boolean, Buffer, ClientData));
    201 #ifdef SYSVVARSUB
    202 static Boolean VarSYSVMatch __P((char *, Boolean, Buffer, ClientData));
    203 #endif
    204 static Boolean VarNoMatch __P((char *, Boolean, Buffer, ClientData));
    205 #ifndef NO_REGEX
    206 static void VarREError __P((int, regex_t *, const char *));
    207 static Boolean VarRESubstitute __P((char *, Boolean, Buffer, ClientData));
    208 #endif
    209 static Boolean VarSubstitute __P((char *, Boolean, Buffer, ClientData));
    210 static Boolean VarLoopExpand __P((char *, Boolean, Buffer, ClientData));
    211 static char *VarGetPattern __P((GNode *, int, char **, int, int *, int *,
    212 				VarPattern *));
    213 static char *VarQuote __P((char *));
    214 static char *VarModify __P((char *, Boolean (*)(char *, Boolean, Buffer,
    215 						ClientData),
    216 			    ClientData));
    217 static char *VarSort __P((char *));
    218 static char *VarUniq __P((char *));
    219 static int VarWordCompare __P((const void *, const void *));
    220 static void VarPrintVar __P((ClientData));
    221 
    222 /*-
    223  *-----------------------------------------------------------------------
    224  * VarFind --
    225  *	Find the given variable in the given context and any other contexts
    226  *	indicated.
    227  *
    228  * Results:
    229  *	A pointer to the structure describing the desired variable or
    230  *	NIL if the variable does not exist.
    231  *
    232  * Side Effects:
    233  *	None
    234  *-----------------------------------------------------------------------
    235  */
    236 static Var *
    237 VarFind (name, ctxt, flags)
    238     char           	*name;	/* name to find */
    239     GNode          	*ctxt;	/* context in which to find it */
    240     int             	flags;	/* FIND_GLOBAL set means to look in the
    241 				 * VAR_GLOBAL context as well.
    242 				 * FIND_CMD set means to look in the VAR_CMD
    243 				 * context also.
    244 				 * FIND_ENV set means to look in the
    245 				 * environment */
    246 {
    247     Hash_Entry         	*var;
    248     Var		  	*v;
    249 
    250 	/*
    251 	 * If the variable name begins with a '.', it could very well be one of
    252 	 * the local ones.  We check the name against all the local variables
    253 	 * and substitute the short version in for 'name' if it matches one of
    254 	 * them.
    255 	 */
    256 	if (*name == '.' && isupper((unsigned char) name[1]))
    257 		switch (name[1]) {
    258 		case 'A':
    259 			if (!strcmp(name, ".ALLSRC"))
    260 				name = ALLSRC;
    261 			if (!strcmp(name, ".ARCHIVE"))
    262 				name = ARCHIVE;
    263 			break;
    264 		case 'I':
    265 			if (!strcmp(name, ".IMPSRC"))
    266 				name = IMPSRC;
    267 			break;
    268 		case 'M':
    269 			if (!strcmp(name, ".MEMBER"))
    270 				name = MEMBER;
    271 			break;
    272 		case 'O':
    273 			if (!strcmp(name, ".OODATE"))
    274 				name = OODATE;
    275 			break;
    276 		case 'P':
    277 			if (!strcmp(name, ".PREFIX"))
    278 				name = PREFIX;
    279 			break;
    280 		case 'T':
    281 			if (!strcmp(name, ".TARGET"))
    282 				name = TARGET;
    283 			break;
    284 		}
    285     /*
    286      * First look for the variable in the given context. If it's not there,
    287      * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
    288      * depending on the FIND_* flags in 'flags'
    289      */
    290     var = Hash_FindEntry (&ctxt->context, name);
    291 
    292     if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
    293 	var = Hash_FindEntry (&VAR_CMD->context, name);
    294     }
    295     if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
    296 	(ctxt != VAR_GLOBAL))
    297     {
    298 	var = Hash_FindEntry (&VAR_GLOBAL->context, name);
    299     }
    300     if ((var == NULL) && (flags & FIND_ENV)) {
    301 	char *env;
    302 
    303 	if ((env = getenv (name)) != NULL) {
    304 	    int	  	len;
    305 
    306 	    v = (Var *) emalloc(sizeof(Var));
    307 	    v->name = estrdup(name);
    308 
    309 	    len = strlen(env);
    310 
    311 	    v->val = Buf_Init(len);
    312 	    Buf_AddBytes(v->val, len, (Byte *)env);
    313 
    314 	    v->flags = VAR_FROM_ENV;
    315 	    return (v);
    316 	} else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
    317 		   (ctxt != VAR_GLOBAL))
    318 	{
    319 	    var = Hash_FindEntry (&VAR_GLOBAL->context, name);
    320 	    if (var == NULL) {
    321 		return ((Var *) NIL);
    322 	    } else {
    323 		return ((Var *)Hash_GetValue(var));
    324 	    }
    325 	} else {
    326 	    return((Var *)NIL);
    327 	}
    328     } else if (var == NULL) {
    329 	return ((Var *) NIL);
    330     } else {
    331 	return ((Var *) Hash_GetValue(var));
    332     }
    333 }
    334 
    335 /*-
    336  *-----------------------------------------------------------------------
    337  * VarAdd  --
    338  *	Add a new variable of name name and value val to the given context
    339  *
    340  * Results:
    341  *	None
    342  *
    343  * Side Effects:
    344  *	The new variable is placed at the front of the given context
    345  *	The name and val arguments are duplicated so they may
    346  *	safely be freed.
    347  *-----------------------------------------------------------------------
    348  */
    349 static void
    350 VarAdd (name, val, ctxt)
    351     char           *name;	/* name of variable to add */
    352     char           *val;	/* value to set it to */
    353     GNode          *ctxt;	/* context in which to set it */
    354 {
    355     register Var   *v;
    356     int	    	  len;
    357     Hash_Entry      *h;
    358 
    359     v = (Var *) emalloc (sizeof (Var));
    360 
    361     len = val ? strlen(val) : 0;
    362     v->val = Buf_Init(len+1);
    363     Buf_AddBytes(v->val, len, (Byte *)val);
    364 
    365     v->flags = 0;
    366 
    367     h = Hash_CreateEntry (&ctxt->context, name, NULL);
    368     Hash_SetValue(h, v);
    369     v->name = h->name;
    370     if (DEBUG(VAR)) {
    371 	printf("%s:%s = %s\n", ctxt->name, name, val);
    372     }
    373 }
    374 
    375 /*-
    376  *-----------------------------------------------------------------------
    377  * Var_Delete --
    378  *	Remove a variable from a context.
    379  *
    380  * Results:
    381  *	None.
    382  *
    383  * Side Effects:
    384  *	The Var structure is removed and freed.
    385  *
    386  *-----------------------------------------------------------------------
    387  */
    388 void
    389 Var_Delete(name, ctxt)
    390     char    	  *name;
    391     GNode	  *ctxt;
    392 {
    393     Hash_Entry 	  *ln;
    394 
    395     if (DEBUG(VAR)) {
    396 	printf("%s:delete %s\n", ctxt->name, name);
    397     }
    398     ln = Hash_FindEntry(&ctxt->context, name);
    399     if (ln != NULL) {
    400 	register Var 	  *v;
    401 
    402 	v = (Var *)Hash_GetValue(ln);
    403 	if (v->name != ln->name)
    404 		free(v->name);
    405 	Hash_DeleteEntry(&ctxt->context, ln);
    406 	Buf_Destroy(v->val, TRUE);
    407 	free((Address) v);
    408     }
    409 }
    410 
    411 /*-
    412  *-----------------------------------------------------------------------
    413  * Var_Set --
    414  *	Set the variable name to the value val in the given context.
    415  *
    416  * Results:
    417  *	None.
    418  *
    419  * Side Effects:
    420  *	If the variable doesn't yet exist, a new record is created for it.
    421  *	Else the old value is freed and the new one stuck in its place
    422  *
    423  * Notes:
    424  *	The variable is searched for only in its context before being
    425  *	created in that context. I.e. if the context is VAR_GLOBAL,
    426  *	only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
    427  *	VAR_CMD->context is searched. This is done to avoid the literally
    428  *	thousands of unnecessary strcmp's that used to be done to
    429  *	set, say, $(@) or $(<).
    430  *-----------------------------------------------------------------------
    431  */
    432 void
    433 Var_Set (name, val, ctxt)
    434     char           *name;	/* name of variable to set */
    435     char           *val;	/* value to give to the variable */
    436     GNode          *ctxt;	/* context in which to set it */
    437 {
    438     register Var   *v;
    439     char *cp = name;
    440 
    441     /*
    442      * We only look for a variable in the given context since anything set
    443      * here will override anything in a lower context, so there's not much
    444      * point in searching them all just to save a bit of memory...
    445      */
    446     if ((name = strchr(cp, '$'))) {
    447 	name = Var_Subst(NULL, cp, ctxt, 0);
    448     } else
    449 	name = cp;
    450     v = VarFind (name, ctxt, 0);
    451     if (v == (Var *) NIL) {
    452 	VarAdd (name, val, ctxt);
    453     } else {
    454 	Buf_Discard(v->val, Buf_Size(v->val));
    455 	Buf_AddBytes(v->val, strlen(val), (Byte *)val);
    456 
    457 	if (DEBUG(VAR)) {
    458 	    printf("%s:%s = %s\n", ctxt->name, name, val);
    459 	}
    460     }
    461     /*
    462      * Any variables given on the command line are automatically exported
    463      * to the environment (as per POSIX standard)
    464      */
    465     if (ctxt == VAR_CMD) {
    466 	setenv(name, val, 1);
    467     }
    468     if (name != cp)
    469 	free(name);
    470 }
    471 
    472 /*-
    473  *-----------------------------------------------------------------------
    474  * Var_Append --
    475  *	The variable of the given name has the given value appended to it in
    476  *	the given context.
    477  *
    478  * Results:
    479  *	None
    480  *
    481  * Side Effects:
    482  *	If the variable doesn't exist, it is created. Else the strings
    483  *	are concatenated (with a space in between).
    484  *
    485  * Notes:
    486  *	Only if the variable is being sought in the global context is the
    487  *	environment searched.
    488  *	XXX: Knows its calling circumstances in that if called with ctxt
    489  *	an actual target, it will only search that context since only
    490  *	a local variable could be being appended to. This is actually
    491  *	a big win and must be tolerated.
    492  *-----------------------------------------------------------------------
    493  */
    494 void
    495 Var_Append (name, val, ctxt)
    496     char           *name;	/* Name of variable to modify */
    497     char           *val;	/* String to append to it */
    498     GNode          *ctxt;	/* Context in which this should occur */
    499 {
    500     register Var   *v;
    501     Hash_Entry	   *h;
    502     char *cp = name;
    503 
    504     if ((name = strchr(cp, '$'))) {
    505 	name = Var_Subst(NULL, cp, ctxt, 0);
    506     } else
    507 	name = cp;
    508 
    509     v = VarFind (name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
    510 
    511     if (v == (Var *) NIL) {
    512 	VarAdd (name, val, ctxt);
    513     } else {
    514 	Buf_AddByte(v->val, (Byte)' ');
    515 	Buf_AddBytes(v->val, strlen(val), (Byte *)val);
    516 
    517 	if (DEBUG(VAR)) {
    518 	    printf("%s:%s = %s\n", ctxt->name, name,
    519 		   (char *) Buf_GetAll(v->val, (int *)NULL));
    520 	}
    521 
    522 	if (v->flags & VAR_FROM_ENV) {
    523 	    /*
    524 	     * If the original variable came from the environment, we
    525 	     * have to install it in the global context (we could place
    526 	     * it in the environment, but then we should provide a way to
    527 	     * export other variables...)
    528 	     */
    529 	    v->flags &= ~VAR_FROM_ENV;
    530 	    h = Hash_CreateEntry (&ctxt->context, name, NULL);
    531 	    Hash_SetValue(h, v);
    532 	}
    533     }
    534     if (name != cp)
    535 	free(name);
    536 }
    537 
    538 /*-
    539  *-----------------------------------------------------------------------
    540  * Var_Exists --
    541  *	See if the given variable exists.
    542  *
    543  * Results:
    544  *	TRUE if it does, FALSE if it doesn't
    545  *
    546  * Side Effects:
    547  *	None.
    548  *
    549  *-----------------------------------------------------------------------
    550  */
    551 Boolean
    552 Var_Exists(name, ctxt)
    553     char	  *name;    	/* Variable to find */
    554     GNode	  *ctxt;    	/* Context in which to start search */
    555 {
    556     Var	    	  *v;
    557 
    558     v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
    559 
    560     if (v == (Var *)NIL) {
    561 	return(FALSE);
    562     } else if (v->flags & VAR_FROM_ENV) {
    563 	free(v->name);
    564 	Buf_Destroy(v->val, TRUE);
    565 	free((char *)v);
    566     }
    567     return(TRUE);
    568 }
    569 
    570 /*-
    571  *-----------------------------------------------------------------------
    572  * Var_Value --
    573  *	Return the value of the named variable in the given context
    574  *
    575  * Results:
    576  *	The value if the variable exists, NULL if it doesn't
    577  *
    578  * Side Effects:
    579  *	None
    580  *-----------------------------------------------------------------------
    581  */
    582 char *
    583 Var_Value (name, ctxt, frp)
    584     char           *name;	/* name to find */
    585     GNode          *ctxt;	/* context in which to search for it */
    586     char	   **frp;
    587 {
    588     Var            *v;
    589 
    590     v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
    591     *frp = NULL;
    592     if (v != (Var *) NIL) {
    593 	char *p = ((char *)Buf_GetAll(v->val, (int *)NULL));
    594 	if (v->flags & VAR_FROM_ENV) {
    595 	    free(v->name);
    596 	    Buf_Destroy(v->val, FALSE);
    597 	    free((Address) v);
    598 	    *frp = p;
    599 	}
    600 	return p;
    601     } else {
    602 	return ((char *) NULL);
    603     }
    604 }
    605 
    606 /*-
    607  *-----------------------------------------------------------------------
    608  * VarHead --
    609  *	Remove the tail of the given word and place the result in the given
    610  *	buffer.
    611  *
    612  * Results:
    613  *	TRUE if characters were added to the buffer (a space needs to be
    614  *	added to the buffer before the next word).
    615  *
    616  * Side Effects:
    617  *	The trimmed word is added to the buffer.
    618  *
    619  *-----------------------------------------------------------------------
    620  */
    621 static Boolean
    622 VarHead (word, addSpace, buf, dummy)
    623     char    	  *word;    	/* Word to trim */
    624     Boolean 	  addSpace; 	/* True if need to add a space to the buffer
    625 				 * before sticking in the head */
    626     Buffer  	  buf;	    	/* Buffer in which to store it */
    627     ClientData	  dummy;
    628 {
    629     register char *slash;
    630 
    631     slash = strrchr (word, '/');
    632     if (slash != (char *)NULL) {
    633 	if (addSpace) {
    634 	    Buf_AddByte (buf, (Byte)' ');
    635 	}
    636 	*slash = '\0';
    637 	Buf_AddBytes (buf, strlen (word), (Byte *)word);
    638 	*slash = '/';
    639 	return (TRUE);
    640     } else {
    641 	/*
    642 	 * If no directory part, give . (q.v. the POSIX standard)
    643 	 */
    644 	if (addSpace) {
    645 	    Buf_AddBytes(buf, 2, (Byte *)" .");
    646 	} else {
    647 	    Buf_AddByte(buf, (Byte)'.');
    648 	}
    649     }
    650     return(dummy ? TRUE : TRUE);
    651 }
    652 
    653 /*-
    654  *-----------------------------------------------------------------------
    655  * VarTail --
    656  *	Remove the head of the given word and place the result in the given
    657  *	buffer.
    658  *
    659  * Results:
    660  *	TRUE if characters were added to the buffer (a space needs to be
    661  *	added to the buffer before the next word).
    662  *
    663  * Side Effects:
    664  *	The trimmed word is added to the buffer.
    665  *
    666  *-----------------------------------------------------------------------
    667  */
    668 static Boolean
    669 VarTail (word, addSpace, buf, dummy)
    670     char    	  *word;    	/* Word to trim */
    671     Boolean 	  addSpace; 	/* TRUE if need to stick a space in the
    672 				 * buffer before adding the tail */
    673     Buffer  	  buf;	    	/* Buffer in which to store it */
    674     ClientData	  dummy;
    675 {
    676     register char *slash;
    677 
    678     if (addSpace) {
    679 	Buf_AddByte (buf, (Byte)' ');
    680     }
    681 
    682     slash = strrchr (word, '/');
    683     if (slash != (char *)NULL) {
    684 	*slash++ = '\0';
    685 	Buf_AddBytes (buf, strlen(slash), (Byte *)slash);
    686 	slash[-1] = '/';
    687     } else {
    688 	Buf_AddBytes (buf, strlen(word), (Byte *)word);
    689     }
    690     return (dummy ? TRUE : TRUE);
    691 }
    692 
    693 /*-
    694  *-----------------------------------------------------------------------
    695  * VarSuffix --
    696  *	Place the suffix of the given word in the given buffer.
    697  *
    698  * Results:
    699  *	TRUE if characters were added to the buffer (a space needs to be
    700  *	added to the buffer before the next word).
    701  *
    702  * Side Effects:
    703  *	The suffix from the word is placed in the buffer.
    704  *
    705  *-----------------------------------------------------------------------
    706  */
    707 static Boolean
    708 VarSuffix (word, addSpace, buf, dummy)
    709     char    	  *word;    	/* Word to trim */
    710     Boolean 	  addSpace; 	/* TRUE if need to add a space before placing
    711 				 * the suffix in the buffer */
    712     Buffer  	  buf;	    	/* Buffer in which to store it */
    713     ClientData	  dummy;
    714 {
    715     register char *dot;
    716 
    717     dot = strrchr (word, '.');
    718     if (dot != (char *)NULL) {
    719 	if (addSpace) {
    720 	    Buf_AddByte (buf, (Byte)' ');
    721 	}
    722 	*dot++ = '\0';
    723 	Buf_AddBytes (buf, strlen (dot), (Byte *)dot);
    724 	dot[-1] = '.';
    725 	addSpace = TRUE;
    726     }
    727     return (dummy ? addSpace : addSpace);
    728 }
    729 
    730 /*-
    731  *-----------------------------------------------------------------------
    732  * VarRoot --
    733  *	Remove the suffix of the given word and place the result in the
    734  *	buffer.
    735  *
    736  * Results:
    737  *	TRUE if characters were added to the buffer (a space needs to be
    738  *	added to the buffer before the next word).
    739  *
    740  * Side Effects:
    741  *	The trimmed word is added to the buffer.
    742  *
    743  *-----------------------------------------------------------------------
    744  */
    745 static Boolean
    746 VarRoot (word, addSpace, buf, dummy)
    747     char    	  *word;    	/* Word to trim */
    748     Boolean 	  addSpace; 	/* TRUE if need to add a space to the buffer
    749 				 * before placing the root in it */
    750     Buffer  	  buf;	    	/* Buffer in which to store it */
    751     ClientData	  dummy;
    752 {
    753     register char *dot;
    754 
    755     if (addSpace) {
    756 	Buf_AddByte (buf, (Byte)' ');
    757     }
    758 
    759     dot = strrchr (word, '.');
    760     if (dot != (char *)NULL) {
    761 	*dot = '\0';
    762 	Buf_AddBytes (buf, strlen (word), (Byte *)word);
    763 	*dot = '.';
    764     } else {
    765 	Buf_AddBytes (buf, strlen(word), (Byte *)word);
    766     }
    767     return (dummy ? TRUE : TRUE);
    768 }
    769 
    770 /*-
    771  *-----------------------------------------------------------------------
    772  * VarMatch --
    773  *	Place the word in the buffer if it matches the given pattern.
    774  *	Callback function for VarModify to implement the :M modifier.
    775  *
    776  * Results:
    777  *	TRUE if a space should be placed in the buffer before the next
    778  *	word.
    779  *
    780  * Side Effects:
    781  *	The word may be copied to the buffer.
    782  *
    783  *-----------------------------------------------------------------------
    784  */
    785 static Boolean
    786 VarMatch (word, addSpace, buf, pattern)
    787     char    	  *word;    	/* Word to examine */
    788     Boolean 	  addSpace; 	/* TRUE if need to add a space to the
    789 				 * buffer before adding the word, if it
    790 				 * matches */
    791     Buffer  	  buf;	    	/* Buffer in which to store it */
    792     ClientData    pattern; 	/* Pattern the word must match */
    793 {
    794     if (Str_Match(word, (char *) pattern)) {
    795 	if (addSpace) {
    796 	    Buf_AddByte(buf, (Byte)' ');
    797 	}
    798 	addSpace = TRUE;
    799 	Buf_AddBytes(buf, strlen(word), (Byte *)word);
    800     }
    801     return(addSpace);
    802 }
    803 
    804 #ifdef SYSVVARSUB
    805 /*-
    806  *-----------------------------------------------------------------------
    807  * VarSYSVMatch --
    808  *	Place the word in the buffer if it matches the given pattern.
    809  *	Callback function for VarModify to implement the System V %
    810  *	modifiers.
    811  *
    812  * Results:
    813  *	TRUE if a space should be placed in the buffer before the next
    814  *	word.
    815  *
    816  * Side Effects:
    817  *	The word may be copied to the buffer.
    818  *
    819  *-----------------------------------------------------------------------
    820  */
    821 static Boolean
    822 VarSYSVMatch (word, addSpace, buf, patp)
    823     char    	  *word;    	/* Word to examine */
    824     Boolean 	  addSpace; 	/* TRUE if need to add a space to the
    825 				 * buffer before adding the word, if it
    826 				 * matches */
    827     Buffer  	  buf;	    	/* Buffer in which to store it */
    828     ClientData 	  patp; 	/* Pattern the word must match */
    829 {
    830     int len;
    831     char *ptr;
    832     VarPattern 	  *pat = (VarPattern *) patp;
    833 
    834     if (addSpace)
    835 	Buf_AddByte(buf, (Byte)' ');
    836 
    837     addSpace = TRUE;
    838 
    839     if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL)
    840 	Str_SYSVSubst(buf, pat->rhs, ptr, len);
    841     else
    842 	Buf_AddBytes(buf, strlen(word), (Byte *) word);
    843 
    844     return(addSpace);
    845 }
    846 #endif
    847 
    848 
    849 /*-
    850  *-----------------------------------------------------------------------
    851  * VarNoMatch --
    852  *	Place the word in the buffer if it doesn't match the given pattern.
    853  *	Callback function for VarModify to implement the :N modifier.
    854  *
    855  * Results:
    856  *	TRUE if a space should be placed in the buffer before the next
    857  *	word.
    858  *
    859  * Side Effects:
    860  *	The word may be copied to the buffer.
    861  *
    862  *-----------------------------------------------------------------------
    863  */
    864 static Boolean
    865 VarNoMatch (word, addSpace, buf, pattern)
    866     char    	  *word;    	/* Word to examine */
    867     Boolean 	  addSpace; 	/* TRUE if need to add a space to the
    868 				 * buffer before adding the word, if it
    869 				 * matches */
    870     Buffer  	  buf;	    	/* Buffer in which to store it */
    871     ClientData    pattern; 	/* Pattern the word must match */
    872 {
    873     if (!Str_Match(word, (char *) pattern)) {
    874 	if (addSpace) {
    875 	    Buf_AddByte(buf, (Byte)' ');
    876 	}
    877 	addSpace = TRUE;
    878 	Buf_AddBytes(buf, strlen(word), (Byte *)word);
    879     }
    880     return(addSpace);
    881 }
    882 
    883 
    884 /*-
    885  *-----------------------------------------------------------------------
    886  * VarSubstitute --
    887  *	Perform a string-substitution on the given word, placing the
    888  *	result in the passed buffer.
    889  *
    890  * Results:
    891  *	TRUE if a space is needed before more characters are added.
    892  *
    893  * Side Effects:
    894  *	None.
    895  *
    896  *-----------------------------------------------------------------------
    897  */
    898 static Boolean
    899 VarSubstitute (word, addSpace, buf, patternp)
    900     char    	  	*word;	    /* Word to modify */
    901     Boolean 	  	addSpace;   /* True if space should be added before
    902 				     * other characters */
    903     Buffer  	  	buf;	    /* Buffer for result */
    904     ClientData	        patternp;   /* Pattern for substitution */
    905 {
    906     register int  	wordLen;    /* Length of word */
    907     register char 	*cp;	    /* General pointer */
    908     VarPattern	*pattern = (VarPattern *) patternp;
    909 
    910     wordLen = strlen(word);
    911     if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
    912 	(VAR_SUB_ONE|VAR_SUB_MATCHED)) {
    913 	/*
    914 	 * Still substituting -- break it down into simple anchored cases
    915 	 * and if none of them fits, perform the general substitution case.
    916 	 */
    917 	if ((pattern->flags & VAR_MATCH_START) &&
    918 	    (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
    919 		/*
    920 		 * Anchored at start and beginning of word matches pattern
    921 		 */
    922 		if ((pattern->flags & VAR_MATCH_END) &&
    923 		    (wordLen == pattern->leftLen)) {
    924 			/*
    925 			 * Also anchored at end and matches to the end (word
    926 			 * is same length as pattern) add space and rhs only
    927 			 * if rhs is non-null.
    928 			 */
    929 			if (pattern->rightLen != 0) {
    930 			    if (addSpace) {
    931 				Buf_AddByte(buf, (Byte)' ');
    932 			    }
    933 			    addSpace = TRUE;
    934 			    Buf_AddBytes(buf, pattern->rightLen,
    935 					 (Byte *)pattern->rhs);
    936 			}
    937 			pattern->flags |= VAR_SUB_MATCHED;
    938 		} else if (pattern->flags & VAR_MATCH_END) {
    939 		    /*
    940 		     * Doesn't match to end -- copy word wholesale
    941 		     */
    942 		    goto nosub;
    943 		} else {
    944 		    /*
    945 		     * Matches at start but need to copy in trailing characters
    946 		     */
    947 		    if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
    948 			if (addSpace) {
    949 			    Buf_AddByte(buf, (Byte)' ');
    950 			}
    951 			addSpace = TRUE;
    952 		    }
    953 		    Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
    954 		    Buf_AddBytes(buf, wordLen - pattern->leftLen,
    955 				 (Byte *)(word + pattern->leftLen));
    956 		    pattern->flags |= VAR_SUB_MATCHED;
    957 		}
    958 	} else if (pattern->flags & VAR_MATCH_START) {
    959 	    /*
    960 	     * Had to match at start of word and didn't -- copy whole word.
    961 	     */
    962 	    goto nosub;
    963 	} else if (pattern->flags & VAR_MATCH_END) {
    964 	    /*
    965 	     * Anchored at end, Find only place match could occur (leftLen
    966 	     * characters from the end of the word) and see if it does. Note
    967 	     * that because the $ will be left at the end of the lhs, we have
    968 	     * to use strncmp.
    969 	     */
    970 	    cp = word + (wordLen - pattern->leftLen);
    971 	    if ((cp >= word) &&
    972 		(strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
    973 		/*
    974 		 * Match found. If we will place characters in the buffer,
    975 		 * add a space before hand as indicated by addSpace, then
    976 		 * stuff in the initial, unmatched part of the word followed
    977 		 * by the right-hand-side.
    978 		 */
    979 		if (((cp - word) + pattern->rightLen) != 0) {
    980 		    if (addSpace) {
    981 			Buf_AddByte(buf, (Byte)' ');
    982 		    }
    983 		    addSpace = TRUE;
    984 		}
    985 		Buf_AddBytes(buf, cp - word, (Byte *)word);
    986 		Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
    987 		pattern->flags |= VAR_SUB_MATCHED;
    988 	    } else {
    989 		/*
    990 		 * Had to match at end and didn't. Copy entire word.
    991 		 */
    992 		goto nosub;
    993 	    }
    994 	} else {
    995 	    /*
    996 	     * Pattern is unanchored: search for the pattern in the word using
    997 	     * String_FindSubstring, copying unmatched portions and the
    998 	     * right-hand-side for each match found, handling non-global
    999 	     * substitutions correctly, etc. When the loop is done, any
   1000 	     * remaining part of the word (word and wordLen are adjusted
   1001 	     * accordingly through the loop) is copied straight into the
   1002 	     * buffer.
   1003 	     * addSpace is set FALSE as soon as a space is added to the
   1004 	     * buffer.
   1005 	     */
   1006 	    register Boolean done;
   1007 	    int origSize;
   1008 
   1009 	    done = FALSE;
   1010 	    origSize = Buf_Size(buf);
   1011 	    while (!done) {
   1012 		cp = Str_FindSubstring(word, pattern->lhs);
   1013 		if (cp != (char *)NULL) {
   1014 		    if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
   1015 			Buf_AddByte(buf, (Byte)' ');
   1016 			addSpace = FALSE;
   1017 		    }
   1018 		    Buf_AddBytes(buf, cp-word, (Byte *)word);
   1019 		    Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
   1020 		    wordLen -= (cp - word) + pattern->leftLen;
   1021 		    word = cp + pattern->leftLen;
   1022 		    if (wordLen == 0) {
   1023 			done = TRUE;
   1024 		    }
   1025 		    if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
   1026 			done = TRUE;
   1027 		    }
   1028 		    pattern->flags |= VAR_SUB_MATCHED;
   1029 		} else {
   1030 		    done = TRUE;
   1031 		}
   1032 	    }
   1033 	    if (wordLen != 0) {
   1034 		if (addSpace) {
   1035 		    Buf_AddByte(buf, (Byte)' ');
   1036 		}
   1037 		Buf_AddBytes(buf, wordLen, (Byte *)word);
   1038 	    }
   1039 	    /*
   1040 	     * If added characters to the buffer, need to add a space
   1041 	     * before we add any more. If we didn't add any, just return
   1042 	     * the previous value of addSpace.
   1043 	     */
   1044 	    return ((Buf_Size(buf) != origSize) || addSpace);
   1045 	}
   1046 	return (addSpace);
   1047     }
   1048  nosub:
   1049     if (addSpace) {
   1050 	Buf_AddByte(buf, (Byte)' ');
   1051     }
   1052     Buf_AddBytes(buf, wordLen, (Byte *)word);
   1053     return(TRUE);
   1054 }
   1055 
   1056 #ifndef NO_REGEX
   1057 /*-
   1058  *-----------------------------------------------------------------------
   1059  * VarREError --
   1060  *	Print the error caused by a regcomp or regexec call.
   1061  *
   1062  * Results:
   1063  *	None.
   1064  *
   1065  * Side Effects:
   1066  *	An error gets printed.
   1067  *
   1068  *-----------------------------------------------------------------------
   1069  */
   1070 static void
   1071 VarREError(err, pat, str)
   1072     int err;
   1073     regex_t *pat;
   1074     const char *str;
   1075 {
   1076     char *errbuf;
   1077     int errlen;
   1078 
   1079     errlen = regerror(err, pat, 0, 0);
   1080     errbuf = emalloc(errlen);
   1081     regerror(err, pat, errbuf, errlen);
   1082     Error("%s: %s", str, errbuf);
   1083     free(errbuf);
   1084 }
   1085 
   1086 
   1087 /*-
   1088  *-----------------------------------------------------------------------
   1089  * VarRESubstitute --
   1090  *	Perform a regex substitution on the given word, placing the
   1091  *	result in the passed buffer.
   1092  *
   1093  * Results:
   1094  *	TRUE if a space is needed before more characters are added.
   1095  *
   1096  * Side Effects:
   1097  *	None.
   1098  *
   1099  *-----------------------------------------------------------------------
   1100  */
   1101 static Boolean
   1102 VarRESubstitute(word, addSpace, buf, patternp)
   1103     char *word;
   1104     Boolean addSpace;
   1105     Buffer buf;
   1106     ClientData patternp;
   1107 {
   1108     VarREPattern *pat;
   1109     int xrv;
   1110     char *wp;
   1111     char *rp;
   1112     int added;
   1113     int flags = 0;
   1114 
   1115 #define MAYBE_ADD_SPACE()		\
   1116 	if (addSpace && !added)		\
   1117 	    Buf_AddByte(buf, ' ');	\
   1118 	added = 1
   1119 
   1120     added = 0;
   1121     wp = word;
   1122     pat = patternp;
   1123 
   1124     if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
   1125 	(VAR_SUB_ONE|VAR_SUB_MATCHED))
   1126 	xrv = REG_NOMATCH;
   1127     else {
   1128     tryagain:
   1129 	xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
   1130     }
   1131 
   1132     switch (xrv) {
   1133     case 0:
   1134 	pat->flags |= VAR_SUB_MATCHED;
   1135 	if (pat->matches[0].rm_so > 0) {
   1136 	    MAYBE_ADD_SPACE();
   1137 	    Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
   1138 	}
   1139 
   1140 	for (rp = pat->replace; *rp; rp++) {
   1141 	    if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
   1142 		MAYBE_ADD_SPACE();
   1143 		Buf_AddByte(buf,rp[1]);
   1144 		rp++;
   1145 	    }
   1146 	    else if ((*rp == '&') ||
   1147 		((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
   1148 		int n;
   1149 		char *subbuf;
   1150 		int sublen;
   1151 		char errstr[3];
   1152 
   1153 		if (*rp == '&') {
   1154 		    n = 0;
   1155 		    errstr[0] = '&';
   1156 		    errstr[1] = '\0';
   1157 		} else {
   1158 		    n = rp[1] - '0';
   1159 		    errstr[0] = '\\';
   1160 		    errstr[1] = rp[1];
   1161 		    errstr[2] = '\0';
   1162 		    rp++;
   1163 		}
   1164 
   1165 		if (n > pat->nsub) {
   1166 		    Error("No subexpression %s", &errstr[0]);
   1167 		    subbuf = "";
   1168 		    sublen = 0;
   1169 		} else if ((pat->matches[n].rm_so == -1) &&
   1170 			   (pat->matches[n].rm_eo == -1)) {
   1171 		    Error("No match for subexpression %s", &errstr[0]);
   1172 		    subbuf = "";
   1173 		    sublen = 0;
   1174 	        } else {
   1175 		    subbuf = wp + pat->matches[n].rm_so;
   1176 		    sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
   1177 		}
   1178 
   1179 		if (sublen > 0) {
   1180 		    MAYBE_ADD_SPACE();
   1181 		    Buf_AddBytes(buf, sublen, subbuf);
   1182 		}
   1183 	    } else {
   1184 		MAYBE_ADD_SPACE();
   1185 		Buf_AddByte(buf, *rp);
   1186 	    }
   1187 	}
   1188 	wp += pat->matches[0].rm_eo;
   1189 	if (pat->flags & VAR_SUB_GLOBAL) {
   1190 	    flags |= REG_NOTBOL;
   1191 	    if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
   1192 		MAYBE_ADD_SPACE();
   1193 		Buf_AddByte(buf, *wp);
   1194 		wp++;
   1195 
   1196 	    }
   1197 	    if (*wp)
   1198 		goto tryagain;
   1199 	}
   1200 	if (*wp) {
   1201 	    MAYBE_ADD_SPACE();
   1202 	    Buf_AddBytes(buf, strlen(wp), wp);
   1203 	}
   1204 	break;
   1205     default:
   1206 	VarREError(xrv, &pat->re, "Unexpected regex error");
   1207        /* fall through */
   1208     case REG_NOMATCH:
   1209 	if (*wp) {
   1210 	    MAYBE_ADD_SPACE();
   1211 	    Buf_AddBytes(buf,strlen(wp),wp);
   1212 	}
   1213 	break;
   1214     }
   1215     return(addSpace||added);
   1216 }
   1217 #endif
   1218 
   1219 
   1220 
   1221 /*-
   1222  *-----------------------------------------------------------------------
   1223  * VarLoopExpand --
   1224  *	Implements the :@<temp>@<string>@ modifier of ODE make.
   1225  *	We set the temp variable named in pattern.lhs to word and expand
   1226  *	pattern.rhs storing the result in the passed buffer.
   1227  *
   1228  * Results:
   1229  *	TRUE if a space is needed before more characters are added.
   1230  *
   1231  * Side Effects:
   1232  *	None.
   1233  *
   1234  *-----------------------------------------------------------------------
   1235  */
   1236 static Boolean
   1237 VarLoopExpand (word, addSpace, buf, loopp)
   1238     char    	  	*word;	    /* Word to modify */
   1239     Boolean 	  	addSpace;   /* True if space should be added before
   1240 				     * other characters */
   1241     Buffer  	  	buf;	    /* Buffer for result */
   1242     ClientData	        loopp;      /* Data for substitution */
   1243 {
   1244     VarLoop_t	*loop = (VarLoop_t *) loopp;
   1245     char *s;
   1246     int slen;
   1247 
   1248     Var_Set(loop->tvar, word, loop->ctxt);
   1249     s = Var_Subst(NULL, loop->str, loop->ctxt, loop->err);
   1250     if (s != NULL && *s != '\0') {
   1251 	if (addSpace && *s != '\n')
   1252 	    Buf_AddByte(buf, ' ');
   1253 	Buf_AddBytes(buf, (slen = strlen(s)), (Byte *)s);
   1254 	addSpace = (slen > 0 && s[slen - 1] != '\n');
   1255 	free(s);
   1256     }
   1257     return addSpace;
   1258 }
   1259 
   1260 /*-
   1261  *-----------------------------------------------------------------------
   1262  * VarModify --
   1263  *	Modify each of the words of the passed string using the given
   1264  *	function. Used to implement all modifiers.
   1265  *
   1266  * Results:
   1267  *	A string of all the words modified appropriately.
   1268  *
   1269  * Side Effects:
   1270  *	None.
   1271  *
   1272  *-----------------------------------------------------------------------
   1273  */
   1274 static char *
   1275 VarModify (str, modProc, datum)
   1276     char    	  *str;	    	    /* String whose words should be trimmed */
   1277 				    /* Function to use to modify them */
   1278     Boolean    	  (*modProc) __P((char *, Boolean, Buffer, ClientData));
   1279     ClientData	  datum;    	    /* Datum to pass it */
   1280 {
   1281     Buffer  	  buf;	    	    /* Buffer for the new string */
   1282     Boolean 	  addSpace; 	    /* TRUE if need to add a space to the
   1283 				     * buffer before adding the trimmed
   1284 				     * word */
   1285     char **av;			    /* word list [first word does not count] */
   1286     char *as;			    /* word list memory */
   1287     int ac, i;
   1288 
   1289     buf = Buf_Init (0);
   1290     addSpace = FALSE;
   1291 
   1292     av = brk_string(str, &ac, FALSE, &as);
   1293 
   1294     for (i = 0; i < ac; i++)
   1295 	addSpace = (*modProc)(av[i], addSpace, buf, datum);
   1296 
   1297     free(as);
   1298     free(av);
   1299 
   1300     Buf_AddByte (buf, '\0');
   1301     str = (char *)Buf_GetAll (buf, (int *)NULL);
   1302     Buf_Destroy (buf, FALSE);
   1303     return (str);
   1304 }
   1305 
   1306 
   1307 static int
   1308 VarWordCompare(a, b)
   1309 	const void *a;
   1310 	const void *b;
   1311 {
   1312 	int r = strcmp(*(char **)a, *(char **)b);
   1313 	return r;
   1314 }
   1315 
   1316 /*-
   1317  *-----------------------------------------------------------------------
   1318  * VarSort --
   1319  *	Sort the words in the string.
   1320  *
   1321  * Results:
   1322  *	A string containing the words sorted
   1323  *
   1324  * Side Effects:
   1325  *	None.
   1326  *
   1327  *-----------------------------------------------------------------------
   1328  */
   1329 static char *
   1330 VarSort (str)
   1331     char    	  *str;	    	    /* String whose words should be sorted */
   1332 				    /* Function to use to modify them */
   1333 {
   1334     Buffer  	  buf;	    	    /* Buffer for the new string */
   1335     char **av;			    /* word list [first word does not count] */
   1336     char *as;			    /* word list memory */
   1337     int ac, i;
   1338 
   1339     buf = Buf_Init (0);
   1340 
   1341     av = brk_string(str, &ac, FALSE, &as);
   1342 
   1343     if (ac > 0)
   1344 	qsort(av, ac, sizeof(char *), VarWordCompare);
   1345 
   1346     for (i = 0; i < ac; i++) {
   1347 	Buf_AddBytes(buf, strlen(av[i]), (Byte *) av[i]);
   1348 	if (i != ac - 1)
   1349 	    Buf_AddByte (buf, ' ');
   1350     }
   1351 
   1352     free(as);
   1353     free(av);
   1354 
   1355     Buf_AddByte (buf, '\0');
   1356     str = (char *)Buf_GetAll (buf, (int *)NULL);
   1357     Buf_Destroy (buf, FALSE);
   1358     return (str);
   1359 }
   1360 
   1361 
   1362 /*-
   1363  *-----------------------------------------------------------------------
   1364  * VarUniq --
   1365  *	Remove adjacent duplicate words.
   1366  *
   1367  * Results:
   1368  *	A string containing the resulting words.
   1369  *
   1370  * Side Effects:
   1371  *	None.
   1372  *
   1373  *-----------------------------------------------------------------------
   1374  */
   1375 static char *
   1376 VarUniq(str)
   1377     char 	 *str;	    	    /* String whose words should be sorted */
   1378 				    /* Function to use to modify them */
   1379 {
   1380     Buffer	  buf;	    	    /* Buffer for new string */
   1381     char 	**av;		    /* List of words to affect */
   1382     char 	 *as;		    /* Word list memory */
   1383     int 	  ac, i, j;
   1384 
   1385     buf = Buf_Init(0);
   1386     av = brk_string(str, &ac, FALSE, &as);
   1387 
   1388     if (ac > 1) {
   1389 	for (j = 0, i = 1; i < ac; i++)
   1390 	    if (strcmp(av[i], av[j]) != 0 && (++j != i))
   1391 		av[j] = av[i];
   1392 	ac = j + 1;
   1393     }
   1394 
   1395     for (i = 0; i < ac; i++) {
   1396 	Buf_AddBytes(buf, strlen(av[i]), (Byte *)av[i]);
   1397 	if (i != ac - 1)
   1398 	    Buf_AddByte(buf, ' ');
   1399     }
   1400 
   1401     free(as);
   1402     free(av);
   1403 
   1404     Buf_AddByte(buf, '\0');
   1405     str = (char *)Buf_GetAll(buf, (int *)NULL);
   1406     Buf_Destroy(buf, FALSE);
   1407     return str;
   1408 }
   1409 
   1410 
   1411 /*-
   1412  *-----------------------------------------------------------------------
   1413  * VarGetPattern --
   1414  *	Pass through the tstr looking for 1) escaped delimiters,
   1415  *	'$'s and backslashes (place the escaped character in
   1416  *	uninterpreted) and 2) unescaped $'s that aren't before
   1417  *	the delimiter (expand the variable substitution unless flags
   1418  *	has VAR_NOSUBST set).
   1419  *	Return the expanded string or NULL if the delimiter was missing
   1420  *	If pattern is specified, handle escaped ampersands, and replace
   1421  *	unescaped ampersands with the lhs of the pattern.
   1422  *
   1423  * Results:
   1424  *	A string of all the words modified appropriately.
   1425  *	If length is specified, return the string length of the buffer
   1426  *	If flags is specified and the last character of the pattern is a
   1427  *	$ set the VAR_MATCH_END bit of flags.
   1428  *
   1429  * Side Effects:
   1430  *	None.
   1431  *-----------------------------------------------------------------------
   1432  */
   1433 static char *
   1434 VarGetPattern(ctxt, err, tstr, delim, flags, length, pattern)
   1435     GNode *ctxt;
   1436     int err;
   1437     char **tstr;
   1438     int delim;
   1439     int *flags;
   1440     int *length;
   1441     VarPattern *pattern;
   1442 {
   1443     char *cp;
   1444     Buffer buf = Buf_Init(0);
   1445     int junk;
   1446     if (length == NULL)
   1447 	length = &junk;
   1448 
   1449 #define IS_A_MATCH(cp, delim) \
   1450     ((cp[0] == '\\') && ((cp[1] == delim) ||  \
   1451      (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
   1452 
   1453     /*
   1454      * Skim through until the matching delimiter is found;
   1455      * pick up variable substitutions on the way. Also allow
   1456      * backslashes to quote the delimiter, $, and \, but don't
   1457      * touch other backslashes.
   1458      */
   1459     for (cp = *tstr; *cp && (*cp != delim); cp++) {
   1460 	if (IS_A_MATCH(cp, delim)) {
   1461 	    Buf_AddByte(buf, (Byte) cp[1]);
   1462 	    cp++;
   1463 	} else if (*cp == '$') {
   1464 	    if (cp[1] == delim) {
   1465 		if (flags == NULL)
   1466 		    Buf_AddByte(buf, (Byte) *cp);
   1467 		else
   1468 		    /*
   1469 		     * Unescaped $ at end of pattern => anchor
   1470 		     * pattern at end.
   1471 		     */
   1472 		    *flags |= VAR_MATCH_END;
   1473 	    } else {
   1474 		if (flags == NULL || (*flags & VAR_NOSUBST) == 0) {
   1475 		    char   *cp2;
   1476 		    int     len;
   1477 		    Boolean freeIt;
   1478 
   1479 		    /*
   1480 		     * If unescaped dollar sign not before the
   1481 		     * delimiter, assume it's a variable
   1482 		     * substitution and recurse.
   1483 		     */
   1484 		    cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
   1485 		    Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
   1486 		    if (freeIt)
   1487 			free(cp2);
   1488 		    cp += len - 1;
   1489 		} else {
   1490 		    char *cp2 = &cp[1];
   1491 
   1492 		    if (*cp2 == '(' || *cp2 == '{') {
   1493 			/*
   1494 			 * Find the end of this variable reference
   1495 			 * and suck it in without further ado.
   1496 			 * It will be interperated later.
   1497 			 */
   1498 			int have = *cp2;
   1499 			int want = (*cp2 == '(') ? ')' : '}';
   1500 			int depth = 1;
   1501 
   1502 			for (++cp2; *cp2 != '\0' && depth > 0; ++cp2) {
   1503 			    if (cp2[-1] != '\\') {
   1504 				if (*cp2 == have)
   1505 				    ++depth;
   1506 				if (*cp2 == want)
   1507 				    --depth;
   1508 			    }
   1509 			}
   1510 			Buf_AddBytes(buf, cp2 - cp, (Byte *)cp);
   1511 			cp = --cp2;
   1512 		    } else
   1513 			Buf_AddByte(buf, (Byte) *cp);
   1514 		}
   1515 	    }
   1516 	}
   1517 	else if (pattern && *cp == '&')
   1518 	    Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
   1519 	else
   1520 	    Buf_AddByte(buf, (Byte) *cp);
   1521     }
   1522 
   1523     Buf_AddByte(buf, (Byte) '\0');
   1524 
   1525     if (*cp != delim) {
   1526 	*tstr = cp;
   1527 	*length = 0;
   1528 	return NULL;
   1529     }
   1530     else {
   1531 	*tstr = ++cp;
   1532 	cp = (char *) Buf_GetAll(buf, length);
   1533 	*length -= 1;	/* Don't count the NULL */
   1534 	Buf_Destroy(buf, FALSE);
   1535 	return cp;
   1536     }
   1537 }
   1538 
   1539 /*-
   1540  *-----------------------------------------------------------------------
   1541  * VarQuote --
   1542  *	Quote shell meta-characters in the string
   1543  *
   1544  * Results:
   1545  *	The quoted string
   1546  *
   1547  * Side Effects:
   1548  *	None.
   1549  *
   1550  *-----------------------------------------------------------------------
   1551  */
   1552 static char *
   1553 VarQuote(str)
   1554 	char *str;
   1555 {
   1556 
   1557     Buffer  	  buf;
   1558     /* This should cover most shells :-( */
   1559     static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
   1560 
   1561     buf = Buf_Init (MAKE_BSIZE);
   1562     for (; *str; str++) {
   1563 	if (strchr(meta, *str) != NULL)
   1564 	    Buf_AddByte(buf, (Byte)'\\');
   1565 	Buf_AddByte(buf, (Byte)*str);
   1566     }
   1567     Buf_AddByte(buf, (Byte) '\0');
   1568     str = (char *)Buf_GetAll (buf, (int *)NULL);
   1569     Buf_Destroy (buf, FALSE);
   1570     return str;
   1571 }
   1572 
   1573 
   1574 /*-
   1575  *-----------------------------------------------------------------------
   1576  * Var_Parse --
   1577  *	Given the start of a variable invocation, extract the variable
   1578  *	name and find its value, then modify it according to the
   1579  *	specification.
   1580  *
   1581  * Results:
   1582  *	The (possibly-modified) value of the variable or var_Error if the
   1583  *	specification is invalid. The length of the specification is
   1584  *	placed in *lengthPtr (for invalid specifications, this is just
   1585  *	2...?).
   1586  *	A Boolean in *freePtr telling whether the returned string should
   1587  *	be freed by the caller.
   1588  *
   1589  * Side Effects:
   1590  *	None.
   1591  *
   1592  *-----------------------------------------------------------------------
   1593  */
   1594 char *
   1595 Var_Parse (str, ctxt, err, lengthPtr, freePtr)
   1596     char    	  *str;	    	/* The string to parse */
   1597     GNode   	  *ctxt;    	/* The context for the variable */
   1598     Boolean 	    err;    	/* TRUE if undefined variables are an error */
   1599     int	    	    *lengthPtr;	/* OUT: The length of the specification */
   1600     Boolean 	    *freePtr; 	/* OUT: TRUE if caller should free result */
   1601 {
   1602     register char   *tstr;    	/* Pointer into str */
   1603     Var	    	    *v;	    	/* Variable in invocation */
   1604     char   	    *cp;    	/* Secondary pointer into str (place marker
   1605 				 * for tstr) */
   1606     Boolean 	    haveModifier;/* TRUE if have modifiers for the variable */
   1607     register char   endc;    	/* Ending character when variable in parens
   1608 				 * or braces */
   1609     register char   startc=0;	/* Starting character when variable in parens
   1610 				 * or braces */
   1611     int             cnt;	/* Used to count brace pairs when variable in
   1612 				 * in parens or braces */
   1613     int		    vlen;	/* Length of variable name */
   1614     char    	    *start;
   1615     char	     delim;
   1616     Boolean 	    dynamic;	/* TRUE if the variable is local and we're
   1617 				 * expanding it in a non-local context. This
   1618 				 * is done to support dynamic sources. The
   1619 				 * result is just the invocation, unaltered */
   1620 
   1621     *freePtr = FALSE;
   1622     dynamic = FALSE;
   1623     start = str;
   1624 
   1625     if (str[1] != '(' && str[1] != '{') {
   1626 	/*
   1627 	 * If it's not bounded by braces of some sort, life is much simpler.
   1628 	 * We just need to check for the first character and return the
   1629 	 * value if it exists.
   1630 	 */
   1631 	char	  name[2];
   1632 
   1633 	name[0] = str[1];
   1634 	name[1] = '\0';
   1635 
   1636 	v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   1637 	if (v == (Var *)NIL) {
   1638 	    *lengthPtr = 2;
   1639 
   1640 	    if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
   1641 		/*
   1642 		 * If substituting a local variable in a non-local context,
   1643 		 * assume it's for dynamic source stuff. We have to handle
   1644 		 * this specially and return the longhand for the variable
   1645 		 * with the dollar sign escaped so it makes it back to the
   1646 		 * caller. Only four of the local variables are treated
   1647 		 * specially as they are the only four that will be set
   1648 		 * when dynamic sources are expanded.
   1649 		 */
   1650 		switch (str[1]) {
   1651 		    case '@':
   1652 			return("$(.TARGET)");
   1653 		    case '%':
   1654 			return("$(.ARCHIVE)");
   1655 		    case '*':
   1656 			return("$(.PREFIX)");
   1657 		    case '!':
   1658 			return("$(.MEMBER)");
   1659 		}
   1660 	    }
   1661 	    /*
   1662 	     * Error
   1663 	     */
   1664 	    return (err ? var_Error : varNoError);
   1665 	} else {
   1666 	    haveModifier = FALSE;
   1667 	    tstr = &str[1];
   1668 	    endc = str[1];
   1669 	}
   1670     } else {
   1671 	Buffer buf;	/* Holds the variable name */
   1672 
   1673 	startc = str[1];
   1674 	endc = startc == '(' ? ')' : '}';
   1675 	buf = Buf_Init (MAKE_BSIZE);
   1676 
   1677 	/*
   1678 	 * Skip to the end character or a colon, whichever comes first.
   1679 	 */
   1680 	for (tstr = str + 2;
   1681 	     *tstr != '\0' && *tstr != endc && *tstr != ':';
   1682 	     tstr++)
   1683 	{
   1684 	    /*
   1685 	     * A variable inside a variable, expand
   1686 	     */
   1687 	    if (*tstr == '$') {
   1688 		int rlen;
   1689 		Boolean rfree;
   1690 		char *rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
   1691 		if (rval != NULL) {
   1692 		    Buf_AddBytes(buf, strlen(rval), (Byte *) rval);
   1693 		    if (rfree)
   1694 			free(rval);
   1695 		}
   1696 		tstr += rlen - 1;
   1697 	    }
   1698 	    else
   1699 		Buf_AddByte(buf, (Byte) *tstr);
   1700 	}
   1701 	if (*tstr == ':') {
   1702 	    haveModifier = TRUE;
   1703 	} else if (*tstr != '\0') {
   1704 	    haveModifier = FALSE;
   1705 	} else {
   1706 	    /*
   1707 	     * If we never did find the end character, return NULL
   1708 	     * right now, setting the length to be the distance to
   1709 	     * the end of the string, since that's what make does.
   1710 	     */
   1711 	    *lengthPtr = tstr - str;
   1712 	    return (var_Error);
   1713 	}
   1714 	*tstr = '\0';
   1715 	Buf_AddByte(buf, (Byte) '\0');
   1716 	str = Buf_GetAll(buf, (int *) NULL);
   1717 	vlen = strlen(str);
   1718 
   1719 	v = VarFind (str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   1720 	if ((v == (Var *)NIL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
   1721 	    (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
   1722 	{
   1723 	    /*
   1724 	     * Check for bogus D and F forms of local variables since we're
   1725 	     * in a local context and the name is the right length.
   1726 	     */
   1727 	    switch(*str) {
   1728 		case '@':
   1729 		case '%':
   1730 		case '*':
   1731 		case '!':
   1732 		case '>':
   1733 		case '<':
   1734 		{
   1735 		    char    vname[2];
   1736 		    char    *val;
   1737 
   1738 		    /*
   1739 		     * Well, it's local -- go look for it.
   1740 		     */
   1741 		    vname[0] = *str;
   1742 		    vname[1] = '\0';
   1743 		    v = VarFind(vname, ctxt, 0);
   1744 
   1745 		    if (v != (Var *)NIL) {
   1746 			/*
   1747 			 * No need for nested expansion or anything, as we're
   1748 			 * the only one who sets these things and we sure don't
   1749 			 * but nested invocations in them...
   1750 			 */
   1751 			val = (char *)Buf_GetAll(v->val, (int *)NULL);
   1752 
   1753 			if (str[1] == 'D') {
   1754 			    val = VarModify(val, VarHead, (ClientData)0);
   1755 			} else {
   1756 			    val = VarModify(val, VarTail, (ClientData)0);
   1757 			}
   1758 			/*
   1759 			 * Resulting string is dynamically allocated, so
   1760 			 * tell caller to free it.
   1761 			 */
   1762 			*freePtr = TRUE;
   1763 			*lengthPtr = tstr-start+1;
   1764 			*tstr = endc;
   1765 			Buf_Destroy (buf, TRUE);
   1766 			return(val);
   1767 		    }
   1768 		    break;
   1769 		}
   1770 	    }
   1771 	}
   1772 
   1773 	if (v == (Var *)NIL) {
   1774 	    if (((vlen == 1) ||
   1775 		 (((vlen == 2) && (str[1] == 'F' ||
   1776 					 str[1] == 'D')))) &&
   1777 		((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
   1778 	    {
   1779 		/*
   1780 		 * If substituting a local variable in a non-local context,
   1781 		 * assume it's for dynamic source stuff. We have to handle
   1782 		 * this specially and return the longhand for the variable
   1783 		 * with the dollar sign escaped so it makes it back to the
   1784 		 * caller. Only four of the local variables are treated
   1785 		 * specially as they are the only four that will be set
   1786 		 * when dynamic sources are expanded.
   1787 		 */
   1788 		switch (*str) {
   1789 		    case '@':
   1790 		    case '%':
   1791 		    case '*':
   1792 		    case '!':
   1793 			dynamic = TRUE;
   1794 			break;
   1795 		}
   1796 	    } else if ((vlen > 2) && (*str == '.') &&
   1797 		       isupper((unsigned char) str[1]) &&
   1798 		       ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
   1799 	    {
   1800 		int	len;
   1801 
   1802 		len = vlen - 1;
   1803 		if ((strncmp(str, ".TARGET", len) == 0) ||
   1804 		    (strncmp(str, ".ARCHIVE", len) == 0) ||
   1805 		    (strncmp(str, ".PREFIX", len) == 0) ||
   1806 		    (strncmp(str, ".MEMBER", len) == 0))
   1807 		{
   1808 		    dynamic = TRUE;
   1809 		}
   1810 	    }
   1811 
   1812 	    if (!haveModifier) {
   1813 		/*
   1814 		 * No modifiers -- have specification length so we can return
   1815 		 * now.
   1816 		 */
   1817 		*lengthPtr = tstr - start + 1;
   1818 		*tstr = endc;
   1819 		if (dynamic) {
   1820 		    str = emalloc(*lengthPtr + 1);
   1821 		    strncpy(str, start, *lengthPtr);
   1822 		    str[*lengthPtr] = '\0';
   1823 		    *freePtr = TRUE;
   1824 		    Buf_Destroy (buf, TRUE);
   1825 		    return(str);
   1826 		} else {
   1827 		    Buf_Destroy (buf, TRUE);
   1828 		    return (err ? var_Error : varNoError);
   1829 		}
   1830 	    } else {
   1831 		/*
   1832 		 * Still need to get to the end of the variable specification,
   1833 		 * so kludge up a Var structure for the modifications
   1834 		 */
   1835 		v = (Var *) emalloc(sizeof(Var));
   1836 		v->name = str;
   1837 		v->val = Buf_Init(1);
   1838 		v->flags = VAR_JUNK;
   1839 		Buf_Destroy (buf, FALSE);
   1840 	    }
   1841 	} else
   1842 	    Buf_Destroy (buf, TRUE);
   1843     }
   1844 
   1845 
   1846     if (v->flags & VAR_IN_USE) {
   1847 	Fatal("Variable %s is recursive.", v->name);
   1848 	/*NOTREACHED*/
   1849     } else {
   1850 	v->flags |= VAR_IN_USE;
   1851     }
   1852     /*
   1853      * Before doing any modification, we have to make sure the value
   1854      * has been fully expanded. If it looks like recursion might be
   1855      * necessary (there's a dollar sign somewhere in the variable's value)
   1856      * we just call Var_Subst to do any other substitutions that are
   1857      * necessary. Note that the value returned by Var_Subst will have
   1858      * been dynamically-allocated, so it will need freeing when we
   1859      * return.
   1860      */
   1861     str = (char *)Buf_GetAll(v->val, (int *)NULL);
   1862     if (strchr (str, '$') != (char *)NULL) {
   1863 	str = Var_Subst(NULL, str, ctxt, err);
   1864 	*freePtr = TRUE;
   1865     }
   1866 
   1867     v->flags &= ~VAR_IN_USE;
   1868 
   1869     /*
   1870      * Now we need to apply any modifiers the user wants applied.
   1871      * These are:
   1872      *  	  :M<pattern>	words which match the given <pattern>.
   1873      *  	  	    	<pattern> is of the standard file
   1874      *  	  	    	wildcarding form.
   1875      *  	  :N<pattern>	words which do not match the given <pattern>.
   1876      *  	  :S<d><pat1><d><pat2><d>[g]
   1877      *  	  	    	Substitute <pat2> for <pat1> in the value
   1878      *  	  :C<d><pat1><d><pat2><d>[g]
   1879      *  	  	    	Substitute <pat2> for regex <pat1> in the value
   1880      *  	  :H	    	Substitute the head of each word
   1881      *  	  :T	    	Substitute the tail of each word
   1882      *  	  :E	    	Substitute the extension (minus '.') of
   1883      *  	  	    	each word
   1884      *  	  :R	    	Substitute the root of each word
   1885      *  	  	    	(pathname minus the suffix).
   1886      *		  :O		("Order") Sort words in variable.
   1887      *		  :u		("uniq") Remove adjacent duplicate words.
   1888      *		  :?<true-value>:<false-value>
   1889      *				If the variable evaluates to true, return
   1890      *				true value, else return the second value.
   1891      *	    	  :lhs=rhs  	Like :S, but the rhs goes to the end of
   1892      *	    	    	    	the invocation.
   1893      *		  :sh		Treat the current value as a command
   1894      *				to be run, new value is its output.
   1895      * The following added so we can handle ODE makefiles.
   1896      *		  :@<tmpvar>@<newval>@
   1897      *				Assign a temporary local variable <tmpvar>
   1898      *				to the current value of each word in turn
   1899      *				and replace each word with the result of
   1900      *				evaluating <newval>
   1901      *		  :D<newval>	Use <newval> as value if variable defined
   1902      *		  :U<newval>	Use <newval> as value if variable undefined
   1903      *		  :L		Use the name of the variable as the value.
   1904      *		  :P		Use the path of the node that has the same
   1905      *				name as the variable as the value.  This
   1906      *				basically includes an implied :L so that
   1907      *				the common method of refering to the path
   1908      *				of your dependent 'x' in a rule is to use
   1909      *				the form '${x:P}'.
   1910      *		  :!<cmd>!	Run cmd much the same as :sh run's the
   1911      *				current value of the variable.
   1912      * The ::= modifiers, actually assign a value to the variable.
   1913      * Their main purpose is in supporting modifiers of .for loop
   1914      * iterators and other obscure uses.  They always expand to
   1915      * nothing.  In a target rule that would otherwise expand to an
   1916      * empty line they can be preceded with @: to keep make happy.
   1917      * Eg.
   1918      *
   1919      * foo:	.USE
   1920      * .for i in ${.TARGET} ${.TARGET:R}.gz
   1921      * 		@: ${t::=$i}
   1922      *		@echo blah ${t:T}
   1923      * .endfor
   1924      *
   1925      *		  ::=<str>	Assigns <str> as the new value of variable.
   1926      *		  ::?=<str>	Assigns <str> as value of variable if
   1927      *				it was not already set.
   1928      *		  ::+=<str>	Appends <str> to variable.
   1929      *		  ::!=<cmd>	Assigns output of <cmd> as the new value of
   1930      *				variable.
   1931      */
   1932     if ((str != (char *)NULL) && haveModifier) {
   1933 	/*
   1934 	 * Skip initial colon while putting it back.
   1935 	 */
   1936 	*tstr++ = ':';
   1937 	while (*tstr != endc) {
   1938 	    char	*newStr;    /* New value to return */
   1939 	    char	termc;	    /* Character which terminated scan */
   1940 
   1941 	    if (DEBUG(VAR)) {
   1942 		printf("Applying :%c to \"%s\"\n", *tstr, str);
   1943 	    }
   1944 	    switch (*tstr) {
   1945 	        case ':':
   1946 
   1947 		if (tstr[1] == '=' ||
   1948 		    (tstr[2] == '=' &&
   1949 		     (tstr[1] == '!' || tstr[1] == '+' || tstr[1] == '?'))) {
   1950 		    GNode *v_ctxt;		/* context where v belongs */
   1951 		    char *emsg;
   1952 		    VarPattern	pattern;
   1953 		    int	how;
   1954 
   1955 		    ++tstr;
   1956 		    if (v->flags & VAR_JUNK) {
   1957 			/*
   1958 			 * We need to strdup() it incase
   1959 			 * VarGetPattern() recurses.
   1960 			 */
   1961 			v->name = strdup(v->name);
   1962 			v_ctxt = ctxt;
   1963 		    } else if (ctxt != VAR_GLOBAL) {
   1964 			if (VarFind(v->name, ctxt, 0) == (Var *)NIL)
   1965 			    v_ctxt = VAR_GLOBAL;
   1966 			else
   1967 			    v_ctxt = ctxt;
   1968 		    }
   1969 
   1970 		    switch ((how = *tstr)) {
   1971 		    case '+':
   1972 		    case '?':
   1973 		    case '!':
   1974 			cp = &tstr[2];
   1975 			break;
   1976 		    default:
   1977 			cp = ++tstr;
   1978 			break;
   1979 		    }
   1980 		    delim = '}';
   1981 		    pattern.flags = 0;
   1982 
   1983 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
   1984 						     NULL, &pattern.rightLen, NULL)) == NULL) {
   1985 			if (v->flags & VAR_JUNK) {
   1986 			    free(v->name);
   1987 			    v->name = str;
   1988 			}
   1989 			goto cleanup;
   1990 		    }
   1991 		    termc = *--cp;
   1992 		    delim = '\0';
   1993 
   1994 		    switch (how) {
   1995 		    case '+':
   1996 			Var_Append(v->name, pattern.rhs, v_ctxt);
   1997 			break;
   1998 		    case '!':
   1999 			newStr = Cmd_Exec (pattern.rhs, &emsg);
   2000 			if (emsg)
   2001 			    Error (emsg, str);
   2002 			else
   2003 			   Var_Set(v->name, newStr,  v_ctxt);
   2004 			if (newStr)
   2005 			    free(newStr);
   2006 			break;
   2007 		    case '?':
   2008 			if ((v->flags & VAR_JUNK) == 0)
   2009 			    break;
   2010 			/* FALLTHROUGH */
   2011 		    default:
   2012 			Var_Set(v->name, pattern.rhs, v_ctxt);
   2013 			break;
   2014 		    }
   2015 		    if (v->flags & VAR_JUNK) {
   2016 			free(v->name);
   2017 			v->name = str;
   2018 		    }
   2019 		    free(pattern.rhs);
   2020 		    newStr = var_Error;
   2021 		    break;
   2022 		}
   2023 		goto default_case;
   2024 	        case '@':
   2025 		{
   2026 		    VarLoop_t	loop;
   2027 		    int flags = VAR_NOSUBST;
   2028 
   2029 		    cp = ++tstr;
   2030 		    delim = '@';
   2031 		    if ((loop.tvar = VarGetPattern(ctxt, err, &cp, delim,
   2032 						   &flags, &loop.tvarLen,
   2033 						   NULL)) == NULL)
   2034 			goto cleanup;
   2035 
   2036 		    if ((loop.str = VarGetPattern(ctxt, err, &cp, delim,
   2037 						  &flags, &loop.strLen,
   2038 						  NULL)) == NULL)
   2039 			goto cleanup;
   2040 
   2041 		    termc = *cp;
   2042 		    delim = '\0';
   2043 
   2044 		    loop.err = err;
   2045 		    loop.ctxt = ctxt;
   2046 		    newStr = VarModify(str, VarLoopExpand,
   2047 				       (ClientData)&loop);
   2048 		    free(loop.tvar);
   2049 		    free(loop.str);
   2050 		    break;
   2051 		}
   2052 	        case 'D':
   2053 	        case 'U':
   2054 		{
   2055 		    Buffer  buf;    	/* Buffer for patterns */
   2056 		    int	    wantit;	/* want data in buffer */
   2057 
   2058 		    /*
   2059 		     * Pass through tstr looking for 1) escaped delimiters,
   2060 		     * '$'s and backslashes (place the escaped character in
   2061 		     * uninterpreted) and 2) unescaped $'s that aren't before
   2062 		     * the delimiter (expand the variable substitution).
   2063 		     * The result is left in the Buffer buf.
   2064 		     */
   2065 		    buf = Buf_Init(0);
   2066 		    for (cp = tstr + 1;
   2067 			 *cp != endc && *cp != ':' && *cp != '\0';
   2068 			 cp++) {
   2069 			if ((*cp == '\\') &&
   2070 			    ((cp[1] == ':') ||
   2071 			     (cp[1] == '$') ||
   2072 			     (cp[1] == endc) ||
   2073 			     (cp[1] == '\\')))
   2074 			{
   2075 			    Buf_AddByte(buf, (Byte) cp[1]);
   2076 			    cp++;
   2077 			} else if (*cp == '$') {
   2078 			    /*
   2079 			     * If unescaped dollar sign, assume it's a
   2080 			     * variable substitution and recurse.
   2081 			     */
   2082 			    char    *cp2;
   2083 			    int	    len;
   2084 			    Boolean freeIt;
   2085 
   2086 			    cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
   2087 			    Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
   2088 			    if (freeIt)
   2089 				free(cp2);
   2090 			    cp += len - 1;
   2091 			} else {
   2092 			    Buf_AddByte(buf, (Byte) *cp);
   2093 			}
   2094 		    }
   2095 		    Buf_AddByte(buf, (Byte) '\0');
   2096 
   2097 		    termc = *cp;
   2098 
   2099 		    if (*tstr == 'U')
   2100 			wantit = ((v->flags & VAR_JUNK) != 0);
   2101 		    else
   2102 			wantit = ((v->flags & VAR_JUNK) == 0);
   2103 		    if ((v->flags & VAR_JUNK) != 0)
   2104 			v->flags |= VAR_KEEP;
   2105 		    if (wantit) {
   2106 			newStr = (char *)Buf_GetAll(buf, (int *)NULL);
   2107 			Buf_Destroy(buf, FALSE);
   2108 		    } else {
   2109 			newStr = str;
   2110 			Buf_Destroy(buf, TRUE);
   2111 		    }
   2112 		    break;
   2113 		}
   2114 	        case 'L':
   2115 		{
   2116 		    if ((v->flags & VAR_JUNK) != 0)
   2117 			v->flags |= VAR_KEEP;
   2118 		    newStr = strdup(v->name);
   2119 		    cp = ++tstr;
   2120 		    termc = *tstr;
   2121 		    break;
   2122 		}
   2123 	        case 'P':
   2124 		{
   2125 		    GNode *gn;
   2126 
   2127 		    if ((v->flags & VAR_JUNK) != 0)
   2128 			v->flags |= VAR_KEEP;
   2129 		    gn = Targ_FindNode(v->name, TARG_NOCREATE);
   2130 		    if (gn == NILGNODE || gn->path == NULL)
   2131 			newStr = strdup(v->name);
   2132 		    else
   2133 			newStr = strdup(gn->path);
   2134 		    cp = ++tstr;
   2135 		    termc = *tstr;
   2136 		    break;
   2137 		}
   2138 	        case '!':
   2139 		{
   2140 		    char *emsg;
   2141 		    VarPattern 	    pattern;
   2142 		    pattern.flags = 0;
   2143 
   2144 		    delim = '!';
   2145 
   2146 		    cp = ++tstr;
   2147 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
   2148 						     NULL, &pattern.rightLen, NULL)) == NULL)
   2149 			goto cleanup;
   2150 		    newStr = Cmd_Exec (pattern.rhs, &emsg);
   2151 		    free(pattern.rhs);
   2152 		    if (emsg)
   2153 			Error (emsg, str);
   2154 		    termc = *cp;
   2155 		    delim = '\0';
   2156 		    if (v->flags & VAR_JUNK) {
   2157 			v->flags |= VAR_KEEP;
   2158 		    }
   2159 		    break;
   2160 		}
   2161 		case 'N':
   2162 		case 'M':
   2163 		{
   2164 		    char    *pattern;
   2165 		    char    *cp2;
   2166 		    Boolean copy;
   2167 		    int nest;
   2168 
   2169 		    copy = FALSE;
   2170 		    nest = 1;
   2171 		    for (cp = tstr + 1;
   2172 			 *cp != '\0' && *cp != ':';
   2173 			 cp++)
   2174 		    {
   2175 			if (*cp == '\\' &&
   2176 			    (cp[1] == ':' ||
   2177 			     cp[1] == endc || cp[1] == startc)) {
   2178 			    copy = TRUE;
   2179 			    cp++;
   2180 			    continue;
   2181 			}
   2182 			if (*cp == startc)
   2183 			    ++nest;
   2184 			if (*cp == endc) {
   2185 			    --nest;
   2186 			    if (nest == 0)
   2187 				break;
   2188 			}
   2189 		    }
   2190 		    termc = *cp;
   2191 		    *cp = '\0';
   2192 		    if (copy) {
   2193 			/*
   2194 			 * Need to compress the \:'s out of the pattern, so
   2195 			 * allocate enough room to hold the uncompressed
   2196 			 * pattern (note that cp started at tstr+1, so
   2197 			 * cp - tstr takes the null byte into account) and
   2198 			 * compress the pattern into the space.
   2199 			 */
   2200 			pattern = emalloc(cp - tstr);
   2201 			for (cp2 = pattern, cp = tstr + 1;
   2202 			     *cp != '\0';
   2203 			     cp++, cp2++)
   2204 			{
   2205 			    if ((*cp == '\\') &&
   2206 				(cp[1] == ':' || cp[1] == endc)) {
   2207 				    cp++;
   2208 			    }
   2209 			    *cp2 = *cp;
   2210 			}
   2211 			*cp2 = '\0';
   2212 		    } else {
   2213 			pattern = &tstr[1];
   2214 		    }
   2215 		    if ((cp2 = strchr(pattern, '$'))) {
   2216 			cp2 = pattern;
   2217 			pattern = Var_Subst(NULL, cp2, ctxt, err);
   2218 			if (copy)
   2219 			    free(cp2);
   2220 			copy = TRUE;
   2221 		    }
   2222 		    if (*tstr == 'M' || *tstr == 'm') {
   2223 			newStr = VarModify(str, VarMatch, (ClientData)pattern);
   2224 		    } else {
   2225 			newStr = VarModify(str, VarNoMatch,
   2226 					   (ClientData)pattern);
   2227 		    }
   2228 		    if (copy) {
   2229 			free(pattern);
   2230 		    }
   2231 		    break;
   2232 		}
   2233 		case 'S':
   2234 		{
   2235 		    VarPattern 	    pattern;
   2236 
   2237 		    pattern.flags = 0;
   2238 		    delim = tstr[1];
   2239 		    tstr += 2;
   2240 
   2241 		    /*
   2242 		     * If pattern begins with '^', it is anchored to the
   2243 		     * start of the word -- skip over it and flag pattern.
   2244 		     */
   2245 		    if (*tstr == '^') {
   2246 			pattern.flags |= VAR_MATCH_START;
   2247 			tstr += 1;
   2248 		    }
   2249 
   2250 		    cp = tstr;
   2251 		    if ((pattern.lhs = VarGetPattern(ctxt, err, &cp, delim,
   2252 			&pattern.flags, &pattern.leftLen, NULL)) == NULL)
   2253 			goto cleanup;
   2254 
   2255 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
   2256 			NULL, &pattern.rightLen, &pattern)) == NULL)
   2257 			goto cleanup;
   2258 
   2259 		    /*
   2260 		     * Check for global substitution. If 'g' after the final
   2261 		     * delimiter, substitution is global and is marked that
   2262 		     * way.
   2263 		     */
   2264 		    for (;; cp++) {
   2265 			switch (*cp) {
   2266 			case 'g':
   2267 			    pattern.flags |= VAR_SUB_GLOBAL;
   2268 			    continue;
   2269 			case '1':
   2270 			    pattern.flags |= VAR_SUB_ONE;
   2271 			    continue;
   2272 			}
   2273 			break;
   2274 		    }
   2275 
   2276 		    termc = *cp;
   2277 		    newStr = VarModify(str, VarSubstitute,
   2278 				       (ClientData)&pattern);
   2279 
   2280 		    /*
   2281 		     * Free the two strings.
   2282 		     */
   2283 		    free(pattern.lhs);
   2284 		    free(pattern.rhs);
   2285 		    break;
   2286 		}
   2287 		case '?':
   2288 		{
   2289 		    VarPattern 	pattern;
   2290 		    Boolean	value;
   2291 
   2292 		    /* find ':', and then substitute accordingly */
   2293 
   2294 		    pattern.flags = 0;
   2295 
   2296 		    cp = ++tstr;
   2297 		    delim = ':';
   2298 		    if ((pattern.lhs = VarGetPattern(ctxt, err, &cp, delim,
   2299 			NULL, &pattern.leftLen, NULL)) == NULL)
   2300 			goto cleanup;
   2301 
   2302 		    delim = '}';
   2303 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
   2304 			NULL, &pattern.rightLen, NULL)) == NULL)
   2305 			goto cleanup;
   2306 
   2307 		    termc = *--cp;
   2308 		    delim = '\0';
   2309 		    if (Cond_EvalExpression(1, str, &value, 0) == COND_INVALID){
   2310 			Error("Bad conditional expression `%s' in %s?%s:%s",
   2311 			      str, str, pattern.lhs, pattern.rhs);
   2312 			goto cleanup;
   2313 		    }
   2314 
   2315 		    if (value) {
   2316 			newStr = pattern.lhs;
   2317 			free(pattern.rhs);
   2318 		    } else {
   2319 			newStr = pattern.rhs;
   2320 			free(pattern.lhs);
   2321 		    }
   2322 		    break;
   2323 		}
   2324 #ifndef NO_REGEX
   2325 		case 'C':
   2326 		{
   2327 		    VarREPattern    pattern;
   2328 		    char           *re;
   2329 		    int             error;
   2330 
   2331 		    pattern.flags = 0;
   2332 		    delim = tstr[1];
   2333 		    tstr += 2;
   2334 
   2335 		    cp = tstr;
   2336 
   2337 		    if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
   2338 			NULL, NULL)) == NULL)
   2339 			goto cleanup;
   2340 
   2341 		    if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
   2342 			delim, NULL, NULL, NULL)) == NULL){
   2343 			free(re);
   2344 			goto cleanup;
   2345 		    }
   2346 
   2347 		    for (;; cp++) {
   2348 			switch (*cp) {
   2349 			case 'g':
   2350 			    pattern.flags |= VAR_SUB_GLOBAL;
   2351 			    continue;
   2352 			case '1':
   2353 			    pattern.flags |= VAR_SUB_ONE;
   2354 			    continue;
   2355 			}
   2356 			break;
   2357 		    }
   2358 
   2359 		    termc = *cp;
   2360 
   2361 		    error = regcomp(&pattern.re, re, REG_EXTENDED);
   2362 		    free(re);
   2363 		    if (error)  {
   2364 			*lengthPtr = cp - start + 1;
   2365 			VarREError(error, &pattern.re, "RE substitution error");
   2366 			free(pattern.replace);
   2367 			return (var_Error);
   2368 		    }
   2369 
   2370 		    pattern.nsub = pattern.re.re_nsub + 1;
   2371 		    if (pattern.nsub < 1)
   2372 			pattern.nsub = 1;
   2373 		    if (pattern.nsub > 10)
   2374 			pattern.nsub = 10;
   2375 		    pattern.matches = emalloc(pattern.nsub *
   2376 					      sizeof(regmatch_t));
   2377 		    newStr = VarModify(str, VarRESubstitute,
   2378 				       (ClientData) &pattern);
   2379 		    regfree(&pattern.re);
   2380 		    free(pattern.replace);
   2381 		    free(pattern.matches);
   2382 		    break;
   2383 		}
   2384 #endif
   2385 		case 'Q':
   2386 		    if (tstr[1] == endc || tstr[1] == ':') {
   2387 			newStr = VarQuote (str);
   2388 			cp = tstr + 1;
   2389 			termc = *cp;
   2390 			break;
   2391 		    }
   2392 		    /*FALLTHRU*/
   2393 		case 'T':
   2394 		    if (tstr[1] == endc || tstr[1] == ':') {
   2395 			newStr = VarModify (str, VarTail, (ClientData)0);
   2396 			cp = tstr + 1;
   2397 			termc = *cp;
   2398 			break;
   2399 		    }
   2400 		    /*FALLTHRU*/
   2401 		case 'H':
   2402 		    if (tstr[1] == endc || tstr[1] == ':') {
   2403 			newStr = VarModify (str, VarHead, (ClientData)0);
   2404 			cp = tstr + 1;
   2405 			termc = *cp;
   2406 			break;
   2407 		    }
   2408 		    /*FALLTHRU*/
   2409 		case 'E':
   2410 		    if (tstr[1] == endc || tstr[1] == ':') {
   2411 			newStr = VarModify (str, VarSuffix, (ClientData)0);
   2412 			cp = tstr + 1;
   2413 			termc = *cp;
   2414 			break;
   2415 		    }
   2416 		    /*FALLTHRU*/
   2417 		case 'R':
   2418 		    if (tstr[1] == endc || tstr[1] == ':') {
   2419 			newStr = VarModify (str, VarRoot, (ClientData)0);
   2420 			cp = tstr + 1;
   2421 			termc = *cp;
   2422 			break;
   2423 		    }
   2424 		    /*FALLTHRU*/
   2425 		case 'O':
   2426 		    if (tstr[1] == endc || tstr[1] == ':') {
   2427 			newStr = VarSort (str);
   2428 			cp = tstr + 1;
   2429 			termc = *cp;
   2430 			break;
   2431 		    }
   2432 		    /*FALLTHRU*/
   2433 		case 'u':
   2434 		    if (tstr[1] == endc || tstr[1] == ':') {
   2435 			newStr = VarUniq (str);
   2436 			cp = tstr + 1;
   2437 			termc = *cp;
   2438 			break;
   2439 		    }
   2440 		    /*FALLTHRU*/
   2441 #ifdef SUNSHCMD
   2442 		case 's':
   2443 		    if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
   2444 			char *err;
   2445 			newStr = Cmd_Exec (str, &err);
   2446 			if (err)
   2447 			    Error (err, str);
   2448 			cp = tstr + 2;
   2449 			termc = *cp;
   2450 			break;
   2451 		    }
   2452 		    /*FALLTHRU*/
   2453 #endif
   2454                 default:
   2455 		default_case:
   2456 		{
   2457 #ifdef SYSVVARSUB
   2458 		    /*
   2459 		     * This can either be a bogus modifier or a System-V
   2460 		     * substitution command.
   2461 		     */
   2462 		    VarPattern      pattern;
   2463 		    Boolean         eqFound;
   2464 
   2465 		    pattern.flags = 0;
   2466 		    eqFound = FALSE;
   2467 		    /*
   2468 		     * First we make a pass through the string trying
   2469 		     * to verify it is a SYSV-make-style translation:
   2470 		     * it must be: <string1>=<string2>)
   2471 		     */
   2472 		    cp = tstr;
   2473 		    cnt = 1;
   2474 		    while (*cp != '\0' && cnt) {
   2475 			if (*cp == '=') {
   2476 			    eqFound = TRUE;
   2477 			    /* continue looking for endc */
   2478 			}
   2479 			else if (*cp == endc)
   2480 			    cnt--;
   2481 			else if (*cp == startc)
   2482 			    cnt++;
   2483 			if (cnt)
   2484 			    cp++;
   2485 		    }
   2486 		    if (*cp == endc && eqFound) {
   2487 
   2488 			/*
   2489 			 * Now we break this sucker into the lhs and
   2490 			 * rhs. We must null terminate them of course.
   2491 			 */
   2492 			for (cp = tstr; *cp != '='; cp++)
   2493 			    continue;
   2494 			pattern.lhs = tstr;
   2495 			pattern.leftLen = cp - tstr;
   2496 			*cp++ = '\0';
   2497 
   2498 			pattern.rhs = cp;
   2499 			cnt = 1;
   2500 			while (cnt) {
   2501 			    if (*cp == endc)
   2502 				cnt--;
   2503 			    else if (*cp == startc)
   2504 				cnt++;
   2505 			    if (cnt)
   2506 				cp++;
   2507 			}
   2508 			pattern.rightLen = cp - pattern.rhs;
   2509 			*cp = '\0';
   2510 
   2511 			/*
   2512 			 * SYSV modifications happen through the whole
   2513 			 * string. Note the pattern is anchored at the end.
   2514 			 */
   2515 			newStr = VarModify(str, VarSYSVMatch,
   2516 					   (ClientData)&pattern);
   2517 
   2518 			/*
   2519 			 * Restore the nulled characters
   2520 			 */
   2521 			pattern.lhs[pattern.leftLen] = '=';
   2522 			pattern.rhs[pattern.rightLen] = endc;
   2523 			termc = endc;
   2524 		    } else
   2525 #endif
   2526 		    {
   2527 			Error ("Unknown modifier '%c'\n", *tstr);
   2528 			for (cp = tstr+1;
   2529 			     *cp != ':' && *cp != endc && *cp != '\0';
   2530 			     cp++)
   2531 				 continue;
   2532 			termc = *cp;
   2533 			newStr = var_Error;
   2534 		    }
   2535 		}
   2536 	    }
   2537 	    if (DEBUG(VAR)) {
   2538 		printf("Result is \"%s\"\n", newStr);
   2539 	    }
   2540 
   2541 	    if (newStr != str) {
   2542 		if (*freePtr) {
   2543 		    free (str);
   2544 		}
   2545 		str = newStr;
   2546 		if (str != var_Error && str != varNoError) {
   2547 		    *freePtr = TRUE;
   2548 		} else {
   2549 		    *freePtr = FALSE;
   2550 		}
   2551 	    }
   2552 	    if (termc == '\0') {
   2553 		Error("Unclosed variable specification for %s", v->name);
   2554 	    } else if (termc == ':') {
   2555 		*cp++ = termc;
   2556 	    } else {
   2557 		*cp = termc;
   2558 	    }
   2559 	    tstr = cp;
   2560 	}
   2561 	*lengthPtr = tstr - start + 1;
   2562     } else {
   2563 	*lengthPtr = tstr - start + 1;
   2564 	*tstr = endc;
   2565     }
   2566 
   2567     if (v->flags & VAR_FROM_ENV) {
   2568 	Boolean	  destroy = FALSE;
   2569 
   2570 	if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
   2571 	    destroy = TRUE;
   2572 	} else {
   2573 	    /*
   2574 	     * Returning the value unmodified, so tell the caller to free
   2575 	     * the thing.
   2576 	     */
   2577 	    *freePtr = TRUE;
   2578 	}
   2579 	if (str != (char *)Buf_GetAll(v->val, (int *)NULL))
   2580 	    Buf_Destroy(v->val, destroy);
   2581 	free((Address)v->name);
   2582 	free((Address)v);
   2583     } else if (v->flags & VAR_JUNK) {
   2584 	/*
   2585 	 * Perform any free'ing needed and set *freePtr to FALSE so the caller
   2586 	 * doesn't try to free a static pointer.
   2587 	 * If VAR_KEEP is also set then we want to keep str as is.
   2588 	 */
   2589 	if (!(v->flags & VAR_KEEP)) {
   2590 	    if (*freePtr) {
   2591 		free(str);
   2592 	    }
   2593 	    *freePtr = FALSE;
   2594 	    if (dynamic) {
   2595 		str = emalloc(*lengthPtr + 1);
   2596 		strncpy(str, start, *lengthPtr);
   2597 		str[*lengthPtr] = '\0';
   2598 		*freePtr = TRUE;
   2599 	    } else {
   2600 		str = var_Error;
   2601 	    }
   2602 	}
   2603 	if (str != (char *)Buf_GetAll(v->val, (int *)NULL))
   2604 	    Buf_Destroy(v->val, TRUE);
   2605 	free((Address)v->name);
   2606 	free((Address)v);
   2607     }
   2608     return (str);
   2609 
   2610 cleanup:
   2611     *lengthPtr = cp - start + 1;
   2612     if (*freePtr)
   2613 	free(str);
   2614     if (delim != '\0')
   2615 	Error("Unclosed substitution for %s (%c missing)",
   2616 	      v->name, delim);
   2617     return (var_Error);
   2618 }
   2619 
   2620 /*-
   2621  *-----------------------------------------------------------------------
   2622  * Var_Subst  --
   2623  *	Substitute for all variables in the given string in the given context
   2624  *	If undefErr is TRUE, Parse_Error will be called when an undefined
   2625  *	variable is encountered.
   2626  *
   2627  * Results:
   2628  *	The resulting string.
   2629  *
   2630  * Side Effects:
   2631  *	None. The old string must be freed by the caller
   2632  *-----------------------------------------------------------------------
   2633  */
   2634 char *
   2635 Var_Subst (var, str, ctxt, undefErr)
   2636     char	  *var;		    /* Named variable || NULL for all */
   2637     char 	  *str;	    	    /* the string in which to substitute */
   2638     GNode         *ctxt;	    /* the context wherein to find variables */
   2639     Boolean 	  undefErr; 	    /* TRUE if undefineds are an error */
   2640 {
   2641     Buffer  	  buf;	    	    /* Buffer for forming things */
   2642     char    	  *val;		    /* Value to substitute for a variable */
   2643     int	    	  length;   	    /* Length of the variable invocation */
   2644     Boolean 	  doFree;   	    /* Set true if val should be freed */
   2645     static Boolean errorReported;   /* Set true if an error has already
   2646 				     * been reported to prevent a plethora
   2647 				     * of messages when recursing */
   2648 
   2649     buf = Buf_Init (MAKE_BSIZE);
   2650     errorReported = FALSE;
   2651 
   2652     while (*str) {
   2653 	if (var == NULL && (*str == '$') && (str[1] == '$')) {
   2654 	    /*
   2655 	     * A dollar sign may be escaped either with another dollar sign.
   2656 	     * In such a case, we skip over the escape character and store the
   2657 	     * dollar sign into the buffer directly.
   2658 	     */
   2659 	    str++;
   2660 	    Buf_AddByte(buf, (Byte)*str);
   2661 	    str++;
   2662 	} else if (*str != '$') {
   2663 	    /*
   2664 	     * Skip as many characters as possible -- either to the end of
   2665 	     * the string or to the next dollar sign (variable invocation).
   2666 	     */
   2667 	    char  *cp;
   2668 
   2669 	    for (cp = str++; *str != '$' && *str != '\0'; str++)
   2670 		continue;
   2671 	    Buf_AddBytes(buf, str - cp, (Byte *)cp);
   2672 	} else {
   2673 	    if (var != NULL) {
   2674 		int expand;
   2675 		for (;;) {
   2676 		    if (str[1] != '(' && str[1] != '{') {
   2677 			if (str[1] != *var || strlen(var) > 1) {
   2678 			    Buf_AddBytes(buf, 2, (Byte *) str);
   2679 			    str += 2;
   2680 			    expand = FALSE;
   2681 			}
   2682 			else
   2683 			    expand = TRUE;
   2684 			break;
   2685 		    }
   2686 		    else {
   2687 			char *p;
   2688 
   2689 			/*
   2690 			 * Scan up to the end of the variable name.
   2691 			 */
   2692 			for (p = &str[2]; *p &&
   2693 			     *p != ':' && *p != ')' && *p != '}'; p++)
   2694 			    if (*p == '$')
   2695 				break;
   2696 			/*
   2697 			 * A variable inside the variable. We cannot expand
   2698 			 * the external variable yet, so we try again with
   2699 			 * the nested one
   2700 			 */
   2701 			if (*p == '$') {
   2702 			    Buf_AddBytes(buf, p - str, (Byte *) str);
   2703 			    str = p;
   2704 			    continue;
   2705 			}
   2706 
   2707 			if (strncmp(var, str + 2, p - str - 2) != 0 ||
   2708 			    var[p - str - 2] != '\0') {
   2709 			    /*
   2710 			     * Not the variable we want to expand, scan
   2711 			     * until the next variable
   2712 			     */
   2713 			    for (;*p != '$' && *p != '\0'; p++)
   2714 				continue;
   2715 			    Buf_AddBytes(buf, p - str, (Byte *) str);
   2716 			    str = p;
   2717 			    expand = FALSE;
   2718 			}
   2719 			else
   2720 			    expand = TRUE;
   2721 			break;
   2722 		    }
   2723 		}
   2724 		if (!expand)
   2725 		    continue;
   2726 	    }
   2727 
   2728 	    val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
   2729 
   2730 	    /*
   2731 	     * When we come down here, val should either point to the
   2732 	     * value of this variable, suitably modified, or be NULL.
   2733 	     * Length should be the total length of the potential
   2734 	     * variable invocation (from $ to end character...)
   2735 	     */
   2736 	    if (val == var_Error || val == varNoError) {
   2737 		/*
   2738 		 * If performing old-time variable substitution, skip over
   2739 		 * the variable and continue with the substitution. Otherwise,
   2740 		 * store the dollar sign and advance str so we continue with
   2741 		 * the string...
   2742 		 */
   2743 		if (oldVars) {
   2744 		    str += length;
   2745 		} else if (undefErr) {
   2746 		    /*
   2747 		     * If variable is undefined, complain and skip the
   2748 		     * variable. The complaint will stop us from doing anything
   2749 		     * when the file is parsed.
   2750 		     */
   2751 		    if (!errorReported) {
   2752 			Parse_Error (PARSE_FATAL,
   2753 				     "Undefined variable \"%.*s\"",length,str);
   2754 		    }
   2755 		    str += length;
   2756 		    errorReported = TRUE;
   2757 		} else {
   2758 		    Buf_AddByte (buf, (Byte)*str);
   2759 		    str += 1;
   2760 		}
   2761 	    } else {
   2762 		/*
   2763 		 * We've now got a variable structure to store in. But first,
   2764 		 * advance the string pointer.
   2765 		 */
   2766 		str += length;
   2767 
   2768 		/*
   2769 		 * Copy all the characters from the variable value straight
   2770 		 * into the new string.
   2771 		 */
   2772 		Buf_AddBytes (buf, strlen (val), (Byte *)val);
   2773 		if (doFree) {
   2774 		    free ((Address)val);
   2775 		}
   2776 	    }
   2777 	}
   2778     }
   2779 
   2780     Buf_AddByte (buf, '\0');
   2781     str = (char *)Buf_GetAll (buf, (int *)NULL);
   2782     Buf_Destroy (buf, FALSE);
   2783     return (str);
   2784 }
   2785 
   2786 /*-
   2787  *-----------------------------------------------------------------------
   2788  * Var_GetTail --
   2789  *	Return the tail from each of a list of words. Used to set the
   2790  *	System V local variables.
   2791  *
   2792  * Results:
   2793  *	The resulting string.
   2794  *
   2795  * Side Effects:
   2796  *	None.
   2797  *
   2798  *-----------------------------------------------------------------------
   2799  */
   2800 char *
   2801 Var_GetTail(file)
   2802     char    	*file;	    /* Filename to modify */
   2803 {
   2804     return(VarModify(file, VarTail, (ClientData)0));
   2805 }
   2806 
   2807 /*-
   2808  *-----------------------------------------------------------------------
   2809  * Var_GetHead --
   2810  *	Find the leading components of a (list of) filename(s).
   2811  *	XXX: VarHead does not replace foo by ., as (sun) System V make
   2812  *	does.
   2813  *
   2814  * Results:
   2815  *	The leading components.
   2816  *
   2817  * Side Effects:
   2818  *	None.
   2819  *
   2820  *-----------------------------------------------------------------------
   2821  */
   2822 char *
   2823 Var_GetHead(file)
   2824     char    	*file;	    /* Filename to manipulate */
   2825 {
   2826     return(VarModify(file, VarHead, (ClientData)0));
   2827 }
   2828 
   2829 /*-
   2830  *-----------------------------------------------------------------------
   2831  * Var_Init --
   2832  *	Initialize the module
   2833  *
   2834  * Results:
   2835  *	None
   2836  *
   2837  * Side Effects:
   2838  *	The VAR_CMD and VAR_GLOBAL contexts are created
   2839  *-----------------------------------------------------------------------
   2840  */
   2841 void
   2842 Var_Init ()
   2843 {
   2844     VAR_GLOBAL = Targ_NewGN ("Global");
   2845     VAR_CMD = Targ_NewGN ("Command");
   2846 
   2847 }
   2848 
   2849 
   2850 void
   2851 Var_End ()
   2852 {
   2853 }
   2854 
   2855 
   2856 /****************** PRINT DEBUGGING INFO *****************/
   2857 static void
   2858 VarPrintVar (vp)
   2859     ClientData vp;
   2860 {
   2861     Var    *v = (Var *) vp;
   2862     printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
   2863 }
   2864 
   2865 /*-
   2866  *-----------------------------------------------------------------------
   2867  * Var_Dump --
   2868  *	print all variables in a context
   2869  *-----------------------------------------------------------------------
   2870  */
   2871 void
   2872 Var_Dump (ctxt)
   2873     GNode          *ctxt;
   2874 {
   2875     Hash_Search search;
   2876     Hash_Entry *h;
   2877 
   2878     for (h = Hash_EnumFirst(&ctxt->context, &search);
   2879 	 h != NULL;
   2880 	 h = Hash_EnumNext(&search)) {
   2881 	    VarPrintVar(Hash_GetValue(h));
   2882     }
   2883 }
   2884