Home | History | Annotate | Line # | Download | only in make
var.c revision 1.36
      1 /*	$NetBSD: var.c,v 1.36 1999/09/15 02:56:35 mycroft 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.36 1999/09/15 02:56:35 mycroft 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.36 1999/09/15 02:56:35 mycroft 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 }  Var;
    154 
    155 
    156 /* Var*Pattern flags */
    157 #define VAR_SUB_GLOBAL	0x01	/* Apply substitution globally */
    158 #define VAR_SUB_ONE	0x02	/* Apply substitution to one word */
    159 #define VAR_SUB_MATCHED	0x04	/* There was a match */
    160 #define VAR_MATCH_START	0x08	/* Match at start of word */
    161 #define VAR_MATCH_END	0x10	/* Match at end of word */
    162 
    163 typedef struct {
    164     char    	  *lhs;	    /* String to match */
    165     int	    	   leftLen; /* Length of string */
    166     char    	  *rhs;	    /* Replacement string (w/ &'s removed) */
    167     int	    	  rightLen; /* Length of replacement */
    168     int	    	  flags;
    169 } VarPattern;
    170 
    171 #ifndef NO_REGEX
    172 typedef struct {
    173     regex_t	   re;
    174     int		   nsub;
    175     regmatch_t 	  *matches;
    176     char 	  *replace;
    177     int		   flags;
    178 } VarREPattern;
    179 #endif
    180 
    181 static Var *VarFind __P((char *, GNode *, int));
    182 static void VarAdd __P((char *, char *, GNode *));
    183 static void VarDelete __P((ClientData));
    184 static Boolean VarHead __P((char *, Boolean, Buffer, ClientData));
    185 static Boolean VarTail __P((char *, Boolean, Buffer, ClientData));
    186 static Boolean VarSuffix __P((char *, Boolean, Buffer, ClientData));
    187 static Boolean VarRoot __P((char *, Boolean, Buffer, ClientData));
    188 static Boolean VarMatch __P((char *, Boolean, Buffer, ClientData));
    189 #ifdef SYSVVARSUB
    190 static Boolean VarSYSVMatch __P((char *, Boolean, Buffer, ClientData));
    191 #endif
    192 static Boolean VarNoMatch __P((char *, Boolean, Buffer, ClientData));
    193 #ifndef NO_REGEX
    194 static void VarREError __P((int, regex_t *, const char *));
    195 static Boolean VarRESubstitute __P((char *, Boolean, Buffer, ClientData));
    196 #endif
    197 static Boolean VarSubstitute __P((char *, Boolean, Buffer, ClientData));
    198 static char *VarGetPattern __P((GNode *, int, char **, int, int *, int *,
    199 				VarPattern *));
    200 static char *VarQuote __P((char *));
    201 static char *VarModify __P((char *, Boolean (*)(char *, Boolean, Buffer,
    202 						ClientData),
    203 			    ClientData));
    204 static char *VarSort __P((char *));
    205 static int VarWordCompare __P((const void *, const void *));
    206 static void VarPrintVar __P((ClientData));
    207 
    208 /*-
    209  *-----------------------------------------------------------------------
    210  * VarFind --
    211  *	Find the given variable in the given context and any other contexts
    212  *	indicated.
    213  *
    214  * Results:
    215  *	A pointer to the structure describing the desired variable or
    216  *	NIL if the variable does not exist.
    217  *
    218  * Side Effects:
    219  *	None
    220  *-----------------------------------------------------------------------
    221  */
    222 static Var *
    223 VarFind (name, ctxt, flags)
    224     char           	*name;	/* name to find */
    225     GNode          	*ctxt;	/* context in which to find it */
    226     int             	flags;	/* FIND_GLOBAL set means to look in the
    227 				 * VAR_GLOBAL context as well.
    228 				 * FIND_CMD set means to look in the VAR_CMD
    229 				 * context also.
    230 				 * FIND_ENV set means to look in the
    231 				 * environment */
    232 {
    233     Hash_Entry         	*var;
    234     Var		  	*v;
    235 
    236 	/*
    237 	 * If the variable name begins with a '.', it could very well be one of
    238 	 * the local ones.  We check the name against all the local variables
    239 	 * and substitute the short version in for 'name' if it matches one of
    240 	 * them.
    241 	 */
    242 	if (*name == '.' && isupper((unsigned char) name[1]))
    243 		switch (name[1]) {
    244 		case 'A':
    245 			if (!strcmp(name, ".ALLSRC"))
    246 				name = ALLSRC;
    247 			if (!strcmp(name, ".ARCHIVE"))
    248 				name = ARCHIVE;
    249 			break;
    250 		case 'I':
    251 			if (!strcmp(name, ".IMPSRC"))
    252 				name = IMPSRC;
    253 			break;
    254 		case 'M':
    255 			if (!strcmp(name, ".MEMBER"))
    256 				name = MEMBER;
    257 			break;
    258 		case 'O':
    259 			if (!strcmp(name, ".OODATE"))
    260 				name = OODATE;
    261 			break;
    262 		case 'P':
    263 			if (!strcmp(name, ".PREFIX"))
    264 				name = PREFIX;
    265 			break;
    266 		case 'T':
    267 			if (!strcmp(name, ".TARGET"))
    268 				name = TARGET;
    269 			break;
    270 		}
    271     /*
    272      * First look for the variable in the given context. If it's not there,
    273      * look for it in VAR_CMD, VAR_GLOBAL and the environment, in that order,
    274      * depending on the FIND_* flags in 'flags'
    275      */
    276     var = Hash_FindEntry (&ctxt->context, name);
    277 
    278     if ((var == NULL) && (flags & FIND_CMD) && (ctxt != VAR_CMD)) {
    279 	var = Hash_FindEntry (&VAR_CMD->context, name);
    280     }
    281     if (!checkEnvFirst && (var == NULL) && (flags & FIND_GLOBAL) &&
    282 	(ctxt != VAR_GLOBAL))
    283     {
    284 	var = Hash_FindEntry (&VAR_GLOBAL->context, name);
    285     }
    286     if ((var == NULL) && (flags & FIND_ENV)) {
    287 	char *env;
    288 
    289 	if ((env = getenv (name)) != NULL) {
    290 	    int	  	len;
    291 
    292 	    v = (Var *) emalloc(sizeof(Var));
    293 	    v->name = estrdup(name);
    294 
    295 	    len = strlen(env);
    296 
    297 	    v->val = Buf_Init(len);
    298 	    Buf_AddBytes(v->val, len, (Byte *)env);
    299 
    300 	    v->flags = VAR_FROM_ENV;
    301 	    return (v);
    302 	} else if (checkEnvFirst && (flags & FIND_GLOBAL) &&
    303 		   (ctxt != VAR_GLOBAL))
    304 	{
    305 	    var = Hash_FindEntry (&VAR_GLOBAL->context, name);
    306 	    if (var == NULL) {
    307 		return ((Var *) NIL);
    308 	    } else {
    309 		return ((Var *)Hash_GetValue(var));
    310 	    }
    311 	} else {
    312 	    return((Var *)NIL);
    313 	}
    314     } else if (var == NULL) {
    315 	return ((Var *) NIL);
    316     } else {
    317 	return ((Var *) Hash_GetValue(var));
    318     }
    319 }
    320 
    321 /*-
    322  *-----------------------------------------------------------------------
    323  * VarAdd  --
    324  *	Add a new variable of name name and value val to the given context
    325  *
    326  * Results:
    327  *	None
    328  *
    329  * Side Effects:
    330  *	The new variable is placed at the front of the given context
    331  *	The name and val arguments are duplicated so they may
    332  *	safely be freed.
    333  *-----------------------------------------------------------------------
    334  */
    335 static void
    336 VarAdd (name, val, ctxt)
    337     char           *name;	/* name of variable to add */
    338     char           *val;	/* value to set it to */
    339     GNode          *ctxt;	/* context in which to set it */
    340 {
    341     register Var   *v;
    342     int	    	  len;
    343     Hash_Entry      *h;
    344 
    345     v = (Var *) emalloc (sizeof (Var));
    346 
    347     v->name = estrdup (name);
    348 
    349     len = val ? strlen(val) : 0;
    350     v->val = Buf_Init(len+1);
    351     Buf_AddBytes(v->val, len, (Byte *)val);
    352 
    353     v->flags = 0;
    354 
    355     h = Hash_CreateEntry (&ctxt->context, name, NULL);
    356     Hash_SetValue(h, v);
    357     if (DEBUG(VAR)) {
    358 	printf("%s:%s = %s\n", ctxt->name, name, val);
    359     }
    360 }
    361 
    362 
    363 /*-
    364  *-----------------------------------------------------------------------
    365  * VarDelete  --
    366  *	Delete a variable and all the space associated with it.
    367  *
    368  * Results:
    369  *	None
    370  *
    371  * Side Effects:
    372  *	None
    373  *-----------------------------------------------------------------------
    374  */
    375 static void
    376 VarDelete(vp)
    377     ClientData vp;
    378 {
    379     Var *v = (Var *) vp;
    380     free(v->name);
    381     Buf_Destroy(v->val, TRUE);
    382     free((Address) v);
    383 }
    384 
    385 
    386 
    387 /*-
    388  *-----------------------------------------------------------------------
    389  * Var_Delete --
    390  *	Remove a variable from a context.
    391  *
    392  * Results:
    393  *	None.
    394  *
    395  * Side Effects:
    396  *	The Var structure is removed and freed.
    397  *
    398  *-----------------------------------------------------------------------
    399  */
    400 void
    401 Var_Delete(name, ctxt)
    402     char    	  *name;
    403     GNode	  *ctxt;
    404 {
    405     Hash_Entry 	  *ln;
    406 
    407     if (DEBUG(VAR)) {
    408 	printf("%s:delete %s\n", ctxt->name, name);
    409     }
    410     ln = Hash_FindEntry(&ctxt->context, name);
    411     if (ln != NULL) {
    412 	register Var 	  *v;
    413 
    414 	v = (Var *)Hash_GetValue(ln);
    415 	Hash_DeleteEntry(&ctxt->context, ln);
    416 	VarDelete((ClientData) v);
    417     }
    418 }
    419 
    420 /*-
    421  *-----------------------------------------------------------------------
    422  * Var_Set --
    423  *	Set the variable name to the value val in the given context.
    424  *
    425  * Results:
    426  *	None.
    427  *
    428  * Side Effects:
    429  *	If the variable doesn't yet exist, a new record is created for it.
    430  *	Else the old value is freed and the new one stuck in its place
    431  *
    432  * Notes:
    433  *	The variable is searched for only in its context before being
    434  *	created in that context. I.e. if the context is VAR_GLOBAL,
    435  *	only VAR_GLOBAL->context is searched. Likewise if it is VAR_CMD, only
    436  *	VAR_CMD->context is searched. This is done to avoid the literally
    437  *	thousands of unnecessary strcmp's that used to be done to
    438  *	set, say, $(@) or $(<).
    439  *-----------------------------------------------------------------------
    440  */
    441 void
    442 Var_Set (name, val, ctxt)
    443     char           *name;	/* name of variable to set */
    444     char           *val;	/* value to give to the variable */
    445     GNode          *ctxt;	/* context in which to set it */
    446 {
    447     register Var   *v;
    448 
    449     /*
    450      * We only look for a variable in the given context since anything set
    451      * here will override anything in a lower context, so there's not much
    452      * point in searching them all just to save a bit of memory...
    453      */
    454     v = VarFind (name, ctxt, 0);
    455     if (v == (Var *) NIL) {
    456 	VarAdd (name, val, ctxt);
    457     } else {
    458 	Buf_Discard(v->val, Buf_Size(v->val));
    459 	Buf_AddBytes(v->val, strlen(val), (Byte *)val);
    460 
    461 	if (DEBUG(VAR)) {
    462 	    printf("%s:%s = %s\n", ctxt->name, name, val);
    463 	}
    464     }
    465     /*
    466      * Any variables given on the command line are automatically exported
    467      * to the environment (as per POSIX standard)
    468      */
    469     if (ctxt == VAR_CMD) {
    470 	setenv(name, val, 1);
    471     }
    472 }
    473 
    474 /*-
    475  *-----------------------------------------------------------------------
    476  * Var_Append --
    477  *	The variable of the given name has the given value appended to it in
    478  *	the given context.
    479  *
    480  * Results:
    481  *	None
    482  *
    483  * Side Effects:
    484  *	If the variable doesn't exist, it is created. Else the strings
    485  *	are concatenated (with a space in between).
    486  *
    487  * Notes:
    488  *	Only if the variable is being sought in the global context is the
    489  *	environment searched.
    490  *	XXX: Knows its calling circumstances in that if called with ctxt
    491  *	an actual target, it will only search that context since only
    492  *	a local variable could be being appended to. This is actually
    493  *	a big win and must be tolerated.
    494  *-----------------------------------------------------------------------
    495  */
    496 void
    497 Var_Append (name, val, ctxt)
    498     char           *name;	/* Name of variable to modify */
    499     char           *val;	/* String to append to it */
    500     GNode          *ctxt;	/* Context in which this should occur */
    501 {
    502     register Var   *v;
    503     Hash_Entry	   *h;
    504 
    505     v = VarFind (name, ctxt, (ctxt == VAR_GLOBAL) ? FIND_ENV : 0);
    506 
    507     if (v == (Var *) NIL) {
    508 	VarAdd (name, val, ctxt);
    509     } else {
    510 	Buf_AddByte(v->val, (Byte)' ');
    511 	Buf_AddBytes(v->val, strlen(val), (Byte *)val);
    512 
    513 	if (DEBUG(VAR)) {
    514 	    printf("%s:%s = %s\n", ctxt->name, name,
    515 		   (char *) Buf_GetAll(v->val, (int *)NULL));
    516 	}
    517 
    518 	if (v->flags & VAR_FROM_ENV) {
    519 	    /*
    520 	     * If the original variable came from the environment, we
    521 	     * have to install it in the global context (we could place
    522 	     * it in the environment, but then we should provide a way to
    523 	     * export other variables...)
    524 	     */
    525 	    v->flags &= ~VAR_FROM_ENV;
    526 	    h = Hash_CreateEntry (&ctxt->context, name, NULL);
    527 	    Hash_SetValue(h, v);
    528 	}
    529     }
    530 }
    531 
    532 /*-
    533  *-----------------------------------------------------------------------
    534  * Var_Exists --
    535  *	See if the given variable exists.
    536  *
    537  * Results:
    538  *	TRUE if it does, FALSE if it doesn't
    539  *
    540  * Side Effects:
    541  *	None.
    542  *
    543  *-----------------------------------------------------------------------
    544  */
    545 Boolean
    546 Var_Exists(name, ctxt)
    547     char	  *name;    	/* Variable to find */
    548     GNode	  *ctxt;    	/* Context in which to start search */
    549 {
    550     Var	    	  *v;
    551 
    552     v = VarFind(name, ctxt, FIND_CMD|FIND_GLOBAL|FIND_ENV);
    553 
    554     if (v == (Var *)NIL) {
    555 	return(FALSE);
    556     } else if (v->flags & VAR_FROM_ENV) {
    557 	free(v->name);
    558 	Buf_Destroy(v->val, TRUE);
    559 	free((char *)v);
    560     }
    561     return(TRUE);
    562 }
    563 
    564 /*-
    565  *-----------------------------------------------------------------------
    566  * Var_Value --
    567  *	Return the value of the named variable in the given context
    568  *
    569  * Results:
    570  *	The value if the variable exists, NULL if it doesn't
    571  *
    572  * Side Effects:
    573  *	None
    574  *-----------------------------------------------------------------------
    575  */
    576 char *
    577 Var_Value (name, ctxt, frp)
    578     char           *name;	/* name to find */
    579     GNode          *ctxt;	/* context in which to search for it */
    580     char	   **frp;
    581 {
    582     Var            *v;
    583 
    584     v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
    585     *frp = NULL;
    586     if (v != (Var *) NIL) {
    587 	char *p = ((char *)Buf_GetAll(v->val, (int *)NULL));
    588 	if (v->flags & VAR_FROM_ENV) {
    589 	    free(v->name);
    590 	    Buf_Destroy(v->val, FALSE);
    591 	    free((Address) v);
    592 	    *frp = p;
    593 	}
    594 	return p;
    595     } else {
    596 	return ((char *) NULL);
    597     }
    598 }
    599 
    600 /*-
    601  *-----------------------------------------------------------------------
    602  * VarHead --
    603  *	Remove the tail of the given word and place the result in the given
    604  *	buffer.
    605  *
    606  * Results:
    607  *	TRUE if characters were added to the buffer (a space needs to be
    608  *	added to the buffer before the next word).
    609  *
    610  * Side Effects:
    611  *	The trimmed word is added to the buffer.
    612  *
    613  *-----------------------------------------------------------------------
    614  */
    615 static Boolean
    616 VarHead (word, addSpace, buf, dummy)
    617     char    	  *word;    	/* Word to trim */
    618     Boolean 	  addSpace; 	/* True if need to add a space to the buffer
    619 				 * before sticking in the head */
    620     Buffer  	  buf;	    	/* Buffer in which to store it */
    621     ClientData	  dummy;
    622 {
    623     register char *slash;
    624 
    625     slash = strrchr (word, '/');
    626     if (slash != (char *)NULL) {
    627 	if (addSpace) {
    628 	    Buf_AddByte (buf, (Byte)' ');
    629 	}
    630 	*slash = '\0';
    631 	Buf_AddBytes (buf, strlen (word), (Byte *)word);
    632 	*slash = '/';
    633 	return (TRUE);
    634     } else {
    635 	/*
    636 	 * If no directory part, give . (q.v. the POSIX standard)
    637 	 */
    638 	if (addSpace) {
    639 	    Buf_AddBytes(buf, 2, (Byte *)" .");
    640 	} else {
    641 	    Buf_AddByte(buf, (Byte)'.');
    642 	}
    643     }
    644     return(dummy ? TRUE : TRUE);
    645 }
    646 
    647 /*-
    648  *-----------------------------------------------------------------------
    649  * VarTail --
    650  *	Remove the head of the given word and place the result in the given
    651  *	buffer.
    652  *
    653  * Results:
    654  *	TRUE if characters were added to the buffer (a space needs to be
    655  *	added to the buffer before the next word).
    656  *
    657  * Side Effects:
    658  *	The trimmed word is added to the buffer.
    659  *
    660  *-----------------------------------------------------------------------
    661  */
    662 static Boolean
    663 VarTail (word, addSpace, buf, dummy)
    664     char    	  *word;    	/* Word to trim */
    665     Boolean 	  addSpace; 	/* TRUE if need to stick a space in the
    666 				 * buffer before adding the tail */
    667     Buffer  	  buf;	    	/* Buffer in which to store it */
    668     ClientData	  dummy;
    669 {
    670     register char *slash;
    671 
    672     if (addSpace) {
    673 	Buf_AddByte (buf, (Byte)' ');
    674     }
    675 
    676     slash = strrchr (word, '/');
    677     if (slash != (char *)NULL) {
    678 	*slash++ = '\0';
    679 	Buf_AddBytes (buf, strlen(slash), (Byte *)slash);
    680 	slash[-1] = '/';
    681     } else {
    682 	Buf_AddBytes (buf, strlen(word), (Byte *)word);
    683     }
    684     return (dummy ? TRUE : TRUE);
    685 }
    686 
    687 /*-
    688  *-----------------------------------------------------------------------
    689  * VarSuffix --
    690  *	Place the suffix of the given word in the given buffer.
    691  *
    692  * Results:
    693  *	TRUE if characters were added to the buffer (a space needs to be
    694  *	added to the buffer before the next word).
    695  *
    696  * Side Effects:
    697  *	The suffix from the word is placed in the buffer.
    698  *
    699  *-----------------------------------------------------------------------
    700  */
    701 static Boolean
    702 VarSuffix (word, addSpace, buf, dummy)
    703     char    	  *word;    	/* Word to trim */
    704     Boolean 	  addSpace; 	/* TRUE if need to add a space before placing
    705 				 * the suffix in the buffer */
    706     Buffer  	  buf;	    	/* Buffer in which to store it */
    707     ClientData	  dummy;
    708 {
    709     register char *dot;
    710 
    711     dot = strrchr (word, '.');
    712     if (dot != (char *)NULL) {
    713 	if (addSpace) {
    714 	    Buf_AddByte (buf, (Byte)' ');
    715 	}
    716 	*dot++ = '\0';
    717 	Buf_AddBytes (buf, strlen (dot), (Byte *)dot);
    718 	dot[-1] = '.';
    719 	addSpace = TRUE;
    720     }
    721     return (dummy ? addSpace : addSpace);
    722 }
    723 
    724 /*-
    725  *-----------------------------------------------------------------------
    726  * VarRoot --
    727  *	Remove the suffix of the given word and place the result in the
    728  *	buffer.
    729  *
    730  * Results:
    731  *	TRUE if characters were added to the buffer (a space needs to be
    732  *	added to the buffer before the next word).
    733  *
    734  * Side Effects:
    735  *	The trimmed word is added to the buffer.
    736  *
    737  *-----------------------------------------------------------------------
    738  */
    739 static Boolean
    740 VarRoot (word, addSpace, buf, dummy)
    741     char    	  *word;    	/* Word to trim */
    742     Boolean 	  addSpace; 	/* TRUE if need to add a space to the buffer
    743 				 * before placing the root in it */
    744     Buffer  	  buf;	    	/* Buffer in which to store it */
    745     ClientData	  dummy;
    746 {
    747     register char *dot;
    748 
    749     if (addSpace) {
    750 	Buf_AddByte (buf, (Byte)' ');
    751     }
    752 
    753     dot = strrchr (word, '.');
    754     if (dot != (char *)NULL) {
    755 	*dot = '\0';
    756 	Buf_AddBytes (buf, strlen (word), (Byte *)word);
    757 	*dot = '.';
    758     } else {
    759 	Buf_AddBytes (buf, strlen(word), (Byte *)word);
    760     }
    761     return (dummy ? TRUE : TRUE);
    762 }
    763 
    764 /*-
    765  *-----------------------------------------------------------------------
    766  * VarMatch --
    767  *	Place the word in the buffer if it matches the given pattern.
    768  *	Callback function for VarModify to implement the :M modifier.
    769  *
    770  * Results:
    771  *	TRUE if a space should be placed in the buffer before the next
    772  *	word.
    773  *
    774  * Side Effects:
    775  *	The word may be copied to the buffer.
    776  *
    777  *-----------------------------------------------------------------------
    778  */
    779 static Boolean
    780 VarMatch (word, addSpace, buf, pattern)
    781     char    	  *word;    	/* Word to examine */
    782     Boolean 	  addSpace; 	/* TRUE if need to add a space to the
    783 				 * buffer before adding the word, if it
    784 				 * matches */
    785     Buffer  	  buf;	    	/* Buffer in which to store it */
    786     ClientData    pattern; 	/* Pattern the word must match */
    787 {
    788     if (Str_Match(word, (char *) pattern)) {
    789 	if (addSpace) {
    790 	    Buf_AddByte(buf, (Byte)' ');
    791 	}
    792 	addSpace = TRUE;
    793 	Buf_AddBytes(buf, strlen(word), (Byte *)word);
    794     }
    795     return(addSpace);
    796 }
    797 
    798 #ifdef SYSVVARSUB
    799 /*-
    800  *-----------------------------------------------------------------------
    801  * VarSYSVMatch --
    802  *	Place the word in the buffer if it matches the given pattern.
    803  *	Callback function for VarModify to implement the System V %
    804  *	modifiers.
    805  *
    806  * Results:
    807  *	TRUE if a space should be placed in the buffer before the next
    808  *	word.
    809  *
    810  * Side Effects:
    811  *	The word may be copied to the buffer.
    812  *
    813  *-----------------------------------------------------------------------
    814  */
    815 static Boolean
    816 VarSYSVMatch (word, addSpace, buf, patp)
    817     char    	  *word;    	/* Word to examine */
    818     Boolean 	  addSpace; 	/* TRUE if need to add a space to the
    819 				 * buffer before adding the word, if it
    820 				 * matches */
    821     Buffer  	  buf;	    	/* Buffer in which to store it */
    822     ClientData 	  patp; 	/* Pattern the word must match */
    823 {
    824     int len;
    825     char *ptr;
    826     VarPattern 	  *pat = (VarPattern *) patp;
    827 
    828     if (addSpace)
    829 	Buf_AddByte(buf, (Byte)' ');
    830 
    831     addSpace = TRUE;
    832 
    833     if ((ptr = Str_SYSVMatch(word, pat->lhs, &len)) != NULL)
    834 	Str_SYSVSubst(buf, pat->rhs, ptr, len);
    835     else
    836 	Buf_AddBytes(buf, strlen(word), (Byte *) word);
    837 
    838     return(addSpace);
    839 }
    840 #endif
    841 
    842 
    843 /*-
    844  *-----------------------------------------------------------------------
    845  * VarNoMatch --
    846  *	Place the word in the buffer if it doesn't match the given pattern.
    847  *	Callback function for VarModify to implement the :N modifier.
    848  *
    849  * Results:
    850  *	TRUE if a space should be placed in the buffer before the next
    851  *	word.
    852  *
    853  * Side Effects:
    854  *	The word may be copied to the buffer.
    855  *
    856  *-----------------------------------------------------------------------
    857  */
    858 static Boolean
    859 VarNoMatch (word, addSpace, buf, pattern)
    860     char    	  *word;    	/* Word to examine */
    861     Boolean 	  addSpace; 	/* TRUE if need to add a space to the
    862 				 * buffer before adding the word, if it
    863 				 * matches */
    864     Buffer  	  buf;	    	/* Buffer in which to store it */
    865     ClientData    pattern; 	/* Pattern the word must match */
    866 {
    867     if (!Str_Match(word, (char *) pattern)) {
    868 	if (addSpace) {
    869 	    Buf_AddByte(buf, (Byte)' ');
    870 	}
    871 	addSpace = TRUE;
    872 	Buf_AddBytes(buf, strlen(word), (Byte *)word);
    873     }
    874     return(addSpace);
    875 }
    876 
    877 
    878 /*-
    879  *-----------------------------------------------------------------------
    880  * VarSubstitute --
    881  *	Perform a string-substitution on the given word, placing the
    882  *	result in the passed buffer.
    883  *
    884  * Results:
    885  *	TRUE if a space is needed before more characters are added.
    886  *
    887  * Side Effects:
    888  *	None.
    889  *
    890  *-----------------------------------------------------------------------
    891  */
    892 static Boolean
    893 VarSubstitute (word, addSpace, buf, patternp)
    894     char    	  	*word;	    /* Word to modify */
    895     Boolean 	  	addSpace;   /* True if space should be added before
    896 				     * other characters */
    897     Buffer  	  	buf;	    /* Buffer for result */
    898     ClientData	        patternp;   /* Pattern for substitution */
    899 {
    900     register int  	wordLen;    /* Length of word */
    901     register char 	*cp;	    /* General pointer */
    902     VarPattern	*pattern = (VarPattern *) patternp;
    903 
    904     wordLen = strlen(word);
    905     if ((pattern->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) !=
    906 	(VAR_SUB_ONE|VAR_SUB_MATCHED)) {
    907 	/*
    908 	 * Still substituting -- break it down into simple anchored cases
    909 	 * and if none of them fits, perform the general substitution case.
    910 	 */
    911 	if ((pattern->flags & VAR_MATCH_START) &&
    912 	    (strncmp(word, pattern->lhs, pattern->leftLen) == 0)) {
    913 		/*
    914 		 * Anchored at start and beginning of word matches pattern
    915 		 */
    916 		if ((pattern->flags & VAR_MATCH_END) &&
    917 		    (wordLen == pattern->leftLen)) {
    918 			/*
    919 			 * Also anchored at end and matches to the end (word
    920 			 * is same length as pattern) add space and rhs only
    921 			 * if rhs is non-null.
    922 			 */
    923 			if (pattern->rightLen != 0) {
    924 			    if (addSpace) {
    925 				Buf_AddByte(buf, (Byte)' ');
    926 			    }
    927 			    addSpace = TRUE;
    928 			    Buf_AddBytes(buf, pattern->rightLen,
    929 					 (Byte *)pattern->rhs);
    930 			}
    931 			pattern->flags |= VAR_SUB_MATCHED;
    932 		} else if (pattern->flags & VAR_MATCH_END) {
    933 		    /*
    934 		     * Doesn't match to end -- copy word wholesale
    935 		     */
    936 		    goto nosub;
    937 		} else {
    938 		    /*
    939 		     * Matches at start but need to copy in trailing characters
    940 		     */
    941 		    if ((pattern->rightLen + wordLen - pattern->leftLen) != 0){
    942 			if (addSpace) {
    943 			    Buf_AddByte(buf, (Byte)' ');
    944 			}
    945 			addSpace = TRUE;
    946 		    }
    947 		    Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
    948 		    Buf_AddBytes(buf, wordLen - pattern->leftLen,
    949 				 (Byte *)(word + pattern->leftLen));
    950 		    pattern->flags |= VAR_SUB_MATCHED;
    951 		}
    952 	} else if (pattern->flags & VAR_MATCH_START) {
    953 	    /*
    954 	     * Had to match at start of word and didn't -- copy whole word.
    955 	     */
    956 	    goto nosub;
    957 	} else if (pattern->flags & VAR_MATCH_END) {
    958 	    /*
    959 	     * Anchored at end, Find only place match could occur (leftLen
    960 	     * characters from the end of the word) and see if it does. Note
    961 	     * that because the $ will be left at the end of the lhs, we have
    962 	     * to use strncmp.
    963 	     */
    964 	    cp = word + (wordLen - pattern->leftLen);
    965 	    if ((cp >= word) &&
    966 		(strncmp(cp, pattern->lhs, pattern->leftLen) == 0)) {
    967 		/*
    968 		 * Match found. If we will place characters in the buffer,
    969 		 * add a space before hand as indicated by addSpace, then
    970 		 * stuff in the initial, unmatched part of the word followed
    971 		 * by the right-hand-side.
    972 		 */
    973 		if (((cp - word) + pattern->rightLen) != 0) {
    974 		    if (addSpace) {
    975 			Buf_AddByte(buf, (Byte)' ');
    976 		    }
    977 		    addSpace = TRUE;
    978 		}
    979 		Buf_AddBytes(buf, cp - word, (Byte *)word);
    980 		Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
    981 		pattern->flags |= VAR_SUB_MATCHED;
    982 	    } else {
    983 		/*
    984 		 * Had to match at end and didn't. Copy entire word.
    985 		 */
    986 		goto nosub;
    987 	    }
    988 	} else {
    989 	    /*
    990 	     * Pattern is unanchored: search for the pattern in the word using
    991 	     * String_FindSubstring, copying unmatched portions and the
    992 	     * right-hand-side for each match found, handling non-global
    993 	     * substitutions correctly, etc. When the loop is done, any
    994 	     * remaining part of the word (word and wordLen are adjusted
    995 	     * accordingly through the loop) is copied straight into the
    996 	     * buffer.
    997 	     * addSpace is set FALSE as soon as a space is added to the
    998 	     * buffer.
    999 	     */
   1000 	    register Boolean done;
   1001 	    int origSize;
   1002 
   1003 	    done = FALSE;
   1004 	    origSize = Buf_Size(buf);
   1005 	    while (!done) {
   1006 		cp = Str_FindSubstring(word, pattern->lhs);
   1007 		if (cp != (char *)NULL) {
   1008 		    if (addSpace && (((cp - word) + pattern->rightLen) != 0)){
   1009 			Buf_AddByte(buf, (Byte)' ');
   1010 			addSpace = FALSE;
   1011 		    }
   1012 		    Buf_AddBytes(buf, cp-word, (Byte *)word);
   1013 		    Buf_AddBytes(buf, pattern->rightLen, (Byte *)pattern->rhs);
   1014 		    wordLen -= (cp - word) + pattern->leftLen;
   1015 		    word = cp + pattern->leftLen;
   1016 		    if (wordLen == 0) {
   1017 			done = TRUE;
   1018 		    }
   1019 		    if ((pattern->flags & VAR_SUB_GLOBAL) == 0) {
   1020 			done = TRUE;
   1021 		    }
   1022 		    pattern->flags |= VAR_SUB_MATCHED;
   1023 		} else {
   1024 		    done = TRUE;
   1025 		}
   1026 	    }
   1027 	    if (wordLen != 0) {
   1028 		if (addSpace) {
   1029 		    Buf_AddByte(buf, (Byte)' ');
   1030 		}
   1031 		Buf_AddBytes(buf, wordLen, (Byte *)word);
   1032 	    }
   1033 	    /*
   1034 	     * If added characters to the buffer, need to add a space
   1035 	     * before we add any more. If we didn't add any, just return
   1036 	     * the previous value of addSpace.
   1037 	     */
   1038 	    return ((Buf_Size(buf) != origSize) || addSpace);
   1039 	}
   1040 	return (addSpace);
   1041     }
   1042  nosub:
   1043     if (addSpace) {
   1044 	Buf_AddByte(buf, (Byte)' ');
   1045     }
   1046     Buf_AddBytes(buf, wordLen, (Byte *)word);
   1047     return(TRUE);
   1048 }
   1049 
   1050 #ifndef NO_REGEX
   1051 /*-
   1052  *-----------------------------------------------------------------------
   1053  * VarREError --
   1054  *	Print the error caused by a regcomp or regexec call.
   1055  *
   1056  * Results:
   1057  *	None.
   1058  *
   1059  * Side Effects:
   1060  *	An error gets printed.
   1061  *
   1062  *-----------------------------------------------------------------------
   1063  */
   1064 static void
   1065 VarREError(err, pat, str)
   1066     int err;
   1067     regex_t *pat;
   1068     const char *str;
   1069 {
   1070     char *errbuf;
   1071     int errlen;
   1072 
   1073     errlen = regerror(err, pat, 0, 0);
   1074     errbuf = emalloc(errlen);
   1075     regerror(err, pat, errbuf, errlen);
   1076     Error("%s: %s", str, errbuf);
   1077     free(errbuf);
   1078 }
   1079 
   1080 
   1081 /*-
   1082  *-----------------------------------------------------------------------
   1083  * VarRESubstitute --
   1084  *	Perform a regex substitution on the given word, placing the
   1085  *	result in the passed buffer.
   1086  *
   1087  * Results:
   1088  *	TRUE if a space is needed before more characters are added.
   1089  *
   1090  * Side Effects:
   1091  *	None.
   1092  *
   1093  *-----------------------------------------------------------------------
   1094  */
   1095 static Boolean
   1096 VarRESubstitute(word, addSpace, buf, patternp)
   1097     char *word;
   1098     Boolean addSpace;
   1099     Buffer buf;
   1100     ClientData patternp;
   1101 {
   1102     VarREPattern *pat;
   1103     int xrv;
   1104     char *wp;
   1105     char *rp;
   1106     int added;
   1107     int flags = 0;
   1108 
   1109 #define MAYBE_ADD_SPACE()		\
   1110 	if (addSpace && !added)		\
   1111 	    Buf_AddByte(buf, ' ');	\
   1112 	added = 1
   1113 
   1114     added = 0;
   1115     wp = word;
   1116     pat = patternp;
   1117 
   1118     if ((pat->flags & (VAR_SUB_ONE|VAR_SUB_MATCHED)) ==
   1119 	(VAR_SUB_ONE|VAR_SUB_MATCHED))
   1120 	xrv = REG_NOMATCH;
   1121     else {
   1122     tryagain:
   1123 	xrv = regexec(&pat->re, wp, pat->nsub, pat->matches, flags);
   1124     }
   1125 
   1126     switch (xrv) {
   1127     case 0:
   1128 	pat->flags |= VAR_SUB_MATCHED;
   1129 	if (pat->matches[0].rm_so > 0) {
   1130 	    MAYBE_ADD_SPACE();
   1131 	    Buf_AddBytes(buf, pat->matches[0].rm_so, wp);
   1132 	}
   1133 
   1134 	for (rp = pat->replace; *rp; rp++) {
   1135 	    if ((*rp == '\\') && ((rp[1] == '&') || (rp[1] == '\\'))) {
   1136 		MAYBE_ADD_SPACE();
   1137 		Buf_AddByte(buf,rp[1]);
   1138 		rp++;
   1139 	    }
   1140 	    else if ((*rp == '&') ||
   1141 		((*rp == '\\') && isdigit((unsigned char)rp[1]))) {
   1142 		int n;
   1143 		char *subbuf;
   1144 		int sublen;
   1145 		char errstr[3];
   1146 
   1147 		if (*rp == '&') {
   1148 		    n = 0;
   1149 		    errstr[0] = '&';
   1150 		    errstr[1] = '\0';
   1151 		} else {
   1152 		    n = rp[1] - '0';
   1153 		    errstr[0] = '\\';
   1154 		    errstr[1] = rp[1];
   1155 		    errstr[2] = '\0';
   1156 		    rp++;
   1157 		}
   1158 
   1159 		if (n > pat->nsub) {
   1160 		    Error("No subexpression %s", &errstr[0]);
   1161 		    subbuf = "";
   1162 		    sublen = 0;
   1163 		} else if ((pat->matches[n].rm_so == -1) &&
   1164 			   (pat->matches[n].rm_eo == -1)) {
   1165 		    Error("No match for subexpression %s", &errstr[0]);
   1166 		    subbuf = "";
   1167 		    sublen = 0;
   1168 	        } else {
   1169 		    subbuf = wp + pat->matches[n].rm_so;
   1170 		    sublen = pat->matches[n].rm_eo - pat->matches[n].rm_so;
   1171 		}
   1172 
   1173 		if (sublen > 0) {
   1174 		    MAYBE_ADD_SPACE();
   1175 		    Buf_AddBytes(buf, sublen, subbuf);
   1176 		}
   1177 	    } else {
   1178 		MAYBE_ADD_SPACE();
   1179 		Buf_AddByte(buf, *rp);
   1180 	    }
   1181 	}
   1182 	wp += pat->matches[0].rm_eo;
   1183 	if (pat->flags & VAR_SUB_GLOBAL) {
   1184 	    flags |= REG_NOTBOL;
   1185 	    if (pat->matches[0].rm_so == 0 && pat->matches[0].rm_eo == 0) {
   1186 		MAYBE_ADD_SPACE();
   1187 		Buf_AddByte(buf, *wp);
   1188 		wp++;
   1189 
   1190 	    }
   1191 	    if (*wp)
   1192 		goto tryagain;
   1193 	}
   1194 	if (*wp) {
   1195 	    MAYBE_ADD_SPACE();
   1196 	    Buf_AddBytes(buf, strlen(wp), wp);
   1197 	}
   1198 	break;
   1199     default:
   1200 	VarREError(xrv, &pat->re, "Unexpected regex error");
   1201        /* fall through */
   1202     case REG_NOMATCH:
   1203 	if (*wp) {
   1204 	    MAYBE_ADD_SPACE();
   1205 	    Buf_AddBytes(buf,strlen(wp),wp);
   1206 	}
   1207 	break;
   1208     }
   1209     return(addSpace||added);
   1210 }
   1211 #endif
   1212 
   1213 
   1214 /*-
   1215  *-----------------------------------------------------------------------
   1216  * VarModify --
   1217  *	Modify each of the words of the passed string using the given
   1218  *	function. Used to implement all modifiers.
   1219  *
   1220  * Results:
   1221  *	A string of all the words modified appropriately.
   1222  *
   1223  * Side Effects:
   1224  *	None.
   1225  *
   1226  *-----------------------------------------------------------------------
   1227  */
   1228 static char *
   1229 VarModify (str, modProc, datum)
   1230     char    	  *str;	    	    /* String whose words should be trimmed */
   1231 				    /* Function to use to modify them */
   1232     Boolean    	  (*modProc) __P((char *, Boolean, Buffer, ClientData));
   1233     ClientData	  datum;    	    /* Datum to pass it */
   1234 {
   1235     Buffer  	  buf;	    	    /* Buffer for the new string */
   1236     Boolean 	  addSpace; 	    /* TRUE if need to add a space to the
   1237 				     * buffer before adding the trimmed
   1238 				     * word */
   1239     char **av;			    /* word list [first word does not count] */
   1240     char *as;			    /* word list memory */
   1241     int ac, i;
   1242 
   1243     buf = Buf_Init (0);
   1244     addSpace = FALSE;
   1245 
   1246     av = brk_string(str, &ac, FALSE, &as);
   1247 
   1248     for (i = 0; i < ac; i++)
   1249 	addSpace = (*modProc)(av[i], addSpace, buf, datum);
   1250 
   1251     free(as);
   1252     free(av);
   1253 
   1254     Buf_AddByte (buf, '\0');
   1255     str = (char *)Buf_GetAll (buf, (int *)NULL);
   1256     Buf_Destroy (buf, FALSE);
   1257     return (str);
   1258 }
   1259 
   1260 
   1261 static int
   1262 VarWordCompare(a, b)
   1263 	const void *a;
   1264 	const void *b;
   1265 {
   1266 	int r = strcmp(*(char **)a, *(char **)b);
   1267 	return r;
   1268 }
   1269 
   1270 /*-
   1271  *-----------------------------------------------------------------------
   1272  * VarSort --
   1273  *	Sort the words in the string.
   1274  *
   1275  * Results:
   1276  *	A string containing the words sorted
   1277  *
   1278  * Side Effects:
   1279  *	None.
   1280  *
   1281  *-----------------------------------------------------------------------
   1282  */
   1283 static char *
   1284 VarSort (str)
   1285     char    	  *str;	    	    /* String whose words should be sorted */
   1286 				    /* Function to use to modify them */
   1287 {
   1288     Buffer  	  buf;	    	    /* Buffer for the new string */
   1289     char **av;			    /* word list [first word does not count] */
   1290     char *as;			    /* word list memory */
   1291     int ac, i;
   1292 
   1293     buf = Buf_Init (0);
   1294 
   1295     av = brk_string(str, &ac, FALSE, &as);
   1296 
   1297     if (ac > 0)
   1298 	qsort(av, ac, sizeof(char *), VarWordCompare);
   1299 
   1300     for (i = 0; i < ac; i++) {
   1301 	Buf_AddBytes(buf, strlen(av[i]), (Byte *) av[i]);
   1302 	if (i != ac - 1)
   1303 	    Buf_AddByte (buf, ' ');
   1304     }
   1305 
   1306     free(as);
   1307     free(av);
   1308 
   1309     Buf_AddByte (buf, '\0');
   1310     str = (char *)Buf_GetAll (buf, (int *)NULL);
   1311     Buf_Destroy (buf, FALSE);
   1312     return (str);
   1313 }
   1314 
   1315 
   1316 /*-
   1317  *-----------------------------------------------------------------------
   1318  * VarGetPattern --
   1319  *	Pass through the tstr looking for 1) escaped delimiters,
   1320  *	'$'s and backslashes (place the escaped character in
   1321  *	uninterpreted) and 2) unescaped $'s that aren't before
   1322  *	the delimiter (expand the variable substitution).
   1323  *	Return the expanded string or NULL if the delimiter was missing
   1324  *	If pattern is specified, handle escaped ampersands, and replace
   1325  *	unescaped ampersands with the lhs of the pattern.
   1326  *
   1327  * Results:
   1328  *	A string of all the words modified appropriately.
   1329  *	If length is specified, return the string length of the buffer
   1330  *	If flags is specified and the last character of the pattern is a
   1331  *	$ set the VAR_MATCH_END bit of flags.
   1332  *
   1333  * Side Effects:
   1334  *	None.
   1335  *-----------------------------------------------------------------------
   1336  */
   1337 static char *
   1338 VarGetPattern(ctxt, err, tstr, delim, flags, length, pattern)
   1339     GNode *ctxt;
   1340     int err;
   1341     char **tstr;
   1342     int delim;
   1343     int *flags;
   1344     int *length;
   1345     VarPattern *pattern;
   1346 {
   1347     char *cp;
   1348     Buffer buf = Buf_Init(0);
   1349     int junk;
   1350     if (length == NULL)
   1351 	length = &junk;
   1352 
   1353 #define IS_A_MATCH(cp, delim) \
   1354     ((cp[0] == '\\') && ((cp[1] == delim) ||  \
   1355      (cp[1] == '\\') || (cp[1] == '$') || (pattern && (cp[1] == '&'))))
   1356 
   1357     /*
   1358      * Skim through until the matching delimiter is found;
   1359      * pick up variable substitutions on the way. Also allow
   1360      * backslashes to quote the delimiter, $, and \, but don't
   1361      * touch other backslashes.
   1362      */
   1363     for (cp = *tstr; *cp && (*cp != delim); cp++) {
   1364 	if (IS_A_MATCH(cp, delim)) {
   1365 	    Buf_AddByte(buf, (Byte) cp[1]);
   1366 	    cp++;
   1367 	} else if (*cp == '$') {
   1368 	    if (cp[1] == delim) {
   1369 		if (flags == NULL)
   1370 		    Buf_AddByte(buf, (Byte) *cp);
   1371 		else
   1372 		    /*
   1373 		     * Unescaped $ at end of pattern => anchor
   1374 		     * pattern at end.
   1375 		     */
   1376 		    *flags |= VAR_MATCH_END;
   1377 	    }
   1378 	    else {
   1379 		char   *cp2;
   1380 		int     len;
   1381 		Boolean freeIt;
   1382 
   1383 		/*
   1384 		 * If unescaped dollar sign not before the
   1385 		 * delimiter, assume it's a variable
   1386 		 * substitution and recurse.
   1387 		 */
   1388 		cp2 = Var_Parse(cp, ctxt, err, &len, &freeIt);
   1389 		Buf_AddBytes(buf, strlen(cp2), (Byte *) cp2);
   1390 		if (freeIt)
   1391 		    free(cp2);
   1392 		cp += len - 1;
   1393 	    }
   1394 	}
   1395 	else if (pattern && *cp == '&')
   1396 	    Buf_AddBytes(buf, pattern->leftLen, (Byte *)pattern->lhs);
   1397 	else
   1398 	    Buf_AddByte(buf, (Byte) *cp);
   1399     }
   1400 
   1401     Buf_AddByte(buf, (Byte) '\0');
   1402 
   1403     if (*cp != delim) {
   1404 	*tstr = cp;
   1405 	*length = 0;
   1406 	return NULL;
   1407     }
   1408     else {
   1409 	*tstr = ++cp;
   1410 	cp = (char *) Buf_GetAll(buf, length);
   1411 	*length -= 1;	/* Don't count the NULL */
   1412 	Buf_Destroy(buf, FALSE);
   1413 	return cp;
   1414     }
   1415 }
   1416 
   1417 /*-
   1418  *-----------------------------------------------------------------------
   1419  * VarQuote --
   1420  *	Quote shell meta-characters in the string
   1421  *
   1422  * Results:
   1423  *	The quoted string
   1424  *
   1425  * Side Effects:
   1426  *	None.
   1427  *
   1428  *-----------------------------------------------------------------------
   1429  */
   1430 static char *
   1431 VarQuote(str)
   1432 	char *str;
   1433 {
   1434 
   1435     Buffer  	  buf;
   1436     /* This should cover most shells :-( */
   1437     static char meta[] = "\n \t'`\";&<>()|*?{}[]\\$!#^~";
   1438 
   1439     buf = Buf_Init (MAKE_BSIZE);
   1440     for (; *str; str++) {
   1441 	if (strchr(meta, *str) != NULL)
   1442 	    Buf_AddByte(buf, (Byte)'\\');
   1443 	Buf_AddByte(buf, (Byte)*str);
   1444     }
   1445     Buf_AddByte(buf, (Byte) '\0');
   1446     str = (char *)Buf_GetAll (buf, (int *)NULL);
   1447     Buf_Destroy (buf, FALSE);
   1448     return str;
   1449 }
   1450 
   1451 
   1452 /*-
   1453  *-----------------------------------------------------------------------
   1454  * Var_Parse --
   1455  *	Given the start of a variable invocation, extract the variable
   1456  *	name and find its value, then modify it according to the
   1457  *	specification.
   1458  *
   1459  * Results:
   1460  *	The (possibly-modified) value of the variable or var_Error if the
   1461  *	specification is invalid. The length of the specification is
   1462  *	placed in *lengthPtr (for invalid specifications, this is just
   1463  *	2...?).
   1464  *	A Boolean in *freePtr telling whether the returned string should
   1465  *	be freed by the caller.
   1466  *
   1467  * Side Effects:
   1468  *	None.
   1469  *
   1470  *-----------------------------------------------------------------------
   1471  */
   1472 char *
   1473 Var_Parse (str, ctxt, err, lengthPtr, freePtr)
   1474     char    	  *str;	    	/* The string to parse */
   1475     GNode   	  *ctxt;    	/* The context for the variable */
   1476     Boolean 	    err;    	/* TRUE if undefined variables are an error */
   1477     int	    	    *lengthPtr;	/* OUT: The length of the specification */
   1478     Boolean 	    *freePtr; 	/* OUT: TRUE if caller should free result */
   1479 {
   1480     register char   *tstr;    	/* Pointer into str */
   1481     Var	    	    *v;	    	/* Variable in invocation */
   1482     char   	    *cp;    	/* Secondary pointer into str (place marker
   1483 				 * for tstr) */
   1484     Boolean 	    haveModifier;/* TRUE if have modifiers for the variable */
   1485     register char   endc;    	/* Ending character when variable in parens
   1486 				 * or braces */
   1487     register char   startc=0;	/* Starting character when variable in parens
   1488 				 * or braces */
   1489     int             cnt;	/* Used to count brace pairs when variable in
   1490 				 * in parens or braces */
   1491     int		    vlen;	/* Length of variable name */
   1492     char    	    *start;
   1493     char	     delim;
   1494     Boolean 	    dynamic;	/* TRUE if the variable is local and we're
   1495 				 * expanding it in a non-local context. This
   1496 				 * is done to support dynamic sources. The
   1497 				 * result is just the invocation, unaltered */
   1498 
   1499     *freePtr = FALSE;
   1500     dynamic = FALSE;
   1501     start = str;
   1502 
   1503     if (str[1] != '(' && str[1] != '{') {
   1504 	/*
   1505 	 * If it's not bounded by braces of some sort, life is much simpler.
   1506 	 * We just need to check for the first character and return the
   1507 	 * value if it exists.
   1508 	 */
   1509 	char	  name[2];
   1510 
   1511 	name[0] = str[1];
   1512 	name[1] = '\0';
   1513 
   1514 	v = VarFind (name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   1515 	if (v == (Var *)NIL) {
   1516 	    *lengthPtr = 2;
   1517 
   1518 	    if ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)) {
   1519 		/*
   1520 		 * If substituting a local variable in a non-local context,
   1521 		 * assume it's for dynamic source stuff. We have to handle
   1522 		 * this specially and return the longhand for the variable
   1523 		 * with the dollar sign escaped so it makes it back to the
   1524 		 * caller. Only four of the local variables are treated
   1525 		 * specially as they are the only four that will be set
   1526 		 * when dynamic sources are expanded.
   1527 		 */
   1528 		switch (str[1]) {
   1529 		    case '@':
   1530 			return("$(.TARGET)");
   1531 		    case '%':
   1532 			return("$(.ARCHIVE)");
   1533 		    case '*':
   1534 			return("$(.PREFIX)");
   1535 		    case '!':
   1536 			return("$(.MEMBER)");
   1537 		}
   1538 	    }
   1539 	    /*
   1540 	     * Error
   1541 	     */
   1542 	    return (err ? var_Error : varNoError);
   1543 	} else {
   1544 	    haveModifier = FALSE;
   1545 	    tstr = &str[1];
   1546 	    endc = str[1];
   1547 	}
   1548     } else {
   1549 	Buffer buf;	/* Holds the variable name */
   1550 
   1551 	startc = str[1];
   1552 	endc = startc == '(' ? ')' : '}';
   1553 	buf = Buf_Init (MAKE_BSIZE);
   1554 
   1555 	/*
   1556 	 * Skip to the end character or a colon, whichever comes first.
   1557 	 */
   1558 	for (tstr = str + 2;
   1559 	     *tstr != '\0' && *tstr != endc && *tstr != ':';
   1560 	     tstr++)
   1561 	{
   1562 	    /*
   1563 	     * A variable inside a variable, expand
   1564 	     */
   1565 	    if (*tstr == '$') {
   1566 		int rlen;
   1567 		Boolean rfree;
   1568 		char *rval = Var_Parse(tstr, ctxt, err, &rlen, &rfree);
   1569 		if (rval != NULL) {
   1570 		    Buf_AddBytes(buf, strlen(rval), (Byte *) rval);
   1571 		    if (rfree)
   1572 			free(rval);
   1573 		}
   1574 		tstr += rlen - 1;
   1575 	    }
   1576 	    else
   1577 		Buf_AddByte(buf, (Byte) *tstr);
   1578 	}
   1579 	if (*tstr == ':') {
   1580 	    haveModifier = TRUE;
   1581 	} else if (*tstr != '\0') {
   1582 	    haveModifier = FALSE;
   1583 	} else {
   1584 	    /*
   1585 	     * If we never did find the end character, return NULL
   1586 	     * right now, setting the length to be the distance to
   1587 	     * the end of the string, since that's what make does.
   1588 	     */
   1589 	    *lengthPtr = tstr - str;
   1590 	    return (var_Error);
   1591 	}
   1592 	*tstr = '\0';
   1593 	Buf_AddByte(buf, (Byte) '\0');
   1594 	str = Buf_GetAll(buf, (int *) NULL);
   1595 	vlen = strlen(str);
   1596 
   1597 	v = VarFind (str, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   1598 	if ((v == (Var *)NIL) && (ctxt != VAR_CMD) && (ctxt != VAR_GLOBAL) &&
   1599 	    (vlen == 2) && (str[1] == 'F' || str[1] == 'D'))
   1600 	{
   1601 	    /*
   1602 	     * Check for bogus D and F forms of local variables since we're
   1603 	     * in a local context and the name is the right length.
   1604 	     */
   1605 	    switch(*str) {
   1606 		case '@':
   1607 		case '%':
   1608 		case '*':
   1609 		case '!':
   1610 		case '>':
   1611 		case '<':
   1612 		{
   1613 		    char    vname[2];
   1614 		    char    *val;
   1615 
   1616 		    /*
   1617 		     * Well, it's local -- go look for it.
   1618 		     */
   1619 		    vname[0] = *str;
   1620 		    vname[1] = '\0';
   1621 		    v = VarFind(vname, ctxt, 0);
   1622 
   1623 		    if (v != (Var *)NIL) {
   1624 			/*
   1625 			 * No need for nested expansion or anything, as we're
   1626 			 * the only one who sets these things and we sure don't
   1627 			 * but nested invocations in them...
   1628 			 */
   1629 			val = (char *)Buf_GetAll(v->val, (int *)NULL);
   1630 
   1631 			if (str[1] == 'D') {
   1632 			    val = VarModify(val, VarHead, (ClientData)0);
   1633 			} else {
   1634 			    val = VarModify(val, VarTail, (ClientData)0);
   1635 			}
   1636 			/*
   1637 			 * Resulting string is dynamically allocated, so
   1638 			 * tell caller to free it.
   1639 			 */
   1640 			*freePtr = TRUE;
   1641 			*lengthPtr = tstr-start+1;
   1642 			*tstr = endc;
   1643 			Buf_Destroy (buf, TRUE);
   1644 			return(val);
   1645 		    }
   1646 		    break;
   1647 		}
   1648 	    }
   1649 	}
   1650 
   1651 	if (v == (Var *)NIL) {
   1652 	    if (((vlen == 1) ||
   1653 		 (((vlen == 2) && (str[1] == 'F' ||
   1654 					 str[1] == 'D')))) &&
   1655 		((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
   1656 	    {
   1657 		/*
   1658 		 * If substituting a local variable in a non-local context,
   1659 		 * assume it's for dynamic source stuff. We have to handle
   1660 		 * this specially and return the longhand for the variable
   1661 		 * with the dollar sign escaped so it makes it back to the
   1662 		 * caller. Only four of the local variables are treated
   1663 		 * specially as they are the only four that will be set
   1664 		 * when dynamic sources are expanded.
   1665 		 */
   1666 		switch (*str) {
   1667 		    case '@':
   1668 		    case '%':
   1669 		    case '*':
   1670 		    case '!':
   1671 			dynamic = TRUE;
   1672 			break;
   1673 		}
   1674 	    } else if ((vlen > 2) && (*str == '.') &&
   1675 		       isupper((unsigned char) str[1]) &&
   1676 		       ((ctxt == VAR_CMD) || (ctxt == VAR_GLOBAL)))
   1677 	    {
   1678 		int	len;
   1679 
   1680 		len = vlen - 1;
   1681 		if ((strncmp(str, ".TARGET", len) == 0) ||
   1682 		    (strncmp(str, ".ARCHIVE", len) == 0) ||
   1683 		    (strncmp(str, ".PREFIX", len) == 0) ||
   1684 		    (strncmp(str, ".MEMBER", len) == 0))
   1685 		{
   1686 		    dynamic = TRUE;
   1687 		}
   1688 	    }
   1689 
   1690 	    if (!haveModifier) {
   1691 		/*
   1692 		 * No modifiers -- have specification length so we can return
   1693 		 * now.
   1694 		 */
   1695 		*lengthPtr = tstr - start + 1;
   1696 		*tstr = endc;
   1697 		if (dynamic) {
   1698 		    str = emalloc(*lengthPtr + 1);
   1699 		    strncpy(str, start, *lengthPtr);
   1700 		    str[*lengthPtr] = '\0';
   1701 		    *freePtr = TRUE;
   1702 		    Buf_Destroy (buf, TRUE);
   1703 		    return(str);
   1704 		} else {
   1705 		    Buf_Destroy (buf, TRUE);
   1706 		    return (err ? var_Error : varNoError);
   1707 		}
   1708 	    } else {
   1709 		/*
   1710 		 * Still need to get to the end of the variable specification,
   1711 		 * so kludge up a Var structure for the modifications
   1712 		 */
   1713 		v = (Var *) emalloc(sizeof(Var));
   1714 		v->name = &str[1];
   1715 		v->val = Buf_Init(1);
   1716 		v->flags = VAR_JUNK;
   1717 	    }
   1718 	}
   1719 	Buf_Destroy (buf, TRUE);
   1720     }
   1721 
   1722 
   1723     if (v->flags & VAR_IN_USE) {
   1724 	Fatal("Variable %s is recursive.", v->name);
   1725 	/*NOTREACHED*/
   1726     } else {
   1727 	v->flags |= VAR_IN_USE;
   1728     }
   1729     /*
   1730      * Before doing any modification, we have to make sure the value
   1731      * has been fully expanded. If it looks like recursion might be
   1732      * necessary (there's a dollar sign somewhere in the variable's value)
   1733      * we just call Var_Subst to do any other substitutions that are
   1734      * necessary. Note that the value returned by Var_Subst will have
   1735      * been dynamically-allocated, so it will need freeing when we
   1736      * return.
   1737      */
   1738     str = (char *)Buf_GetAll(v->val, (int *)NULL);
   1739     if (strchr (str, '$') != (char *)NULL) {
   1740 	str = Var_Subst(NULL, str, ctxt, err);
   1741 	*freePtr = TRUE;
   1742     }
   1743 
   1744     v->flags &= ~VAR_IN_USE;
   1745 
   1746     /*
   1747      * Now we need to apply any modifiers the user wants applied.
   1748      * These are:
   1749      *  	  :M<pattern>	words which match the given <pattern>.
   1750      *  	  	    	<pattern> is of the standard file
   1751      *  	  	    	wildcarding form.
   1752      *  	  :S<d><pat1><d><pat2><d>[g]
   1753      *  	  	    	Substitute <pat2> for <pat1> in the value
   1754      *  	  :C<d><pat1><d><pat2><d>[g]
   1755      *  	  	    	Substitute <pat2> for regex <pat1> in the value
   1756      *  	  :H	    	Substitute the head of each word
   1757      *  	  :T	    	Substitute the tail of each word
   1758      *  	  :E	    	Substitute the extension (minus '.') of
   1759      *  	  	    	each word
   1760      *  	  :R	    	Substitute the root of each word
   1761      *  	  	    	(pathname minus the suffix).
   1762      *		  :O		Sort words in variable.
   1763      *		  :?<true-value>:<false-value>
   1764      *				If the variable evaluates to true, return
   1765      *				true value, else return the second value.
   1766      *	    	  :lhs=rhs  	Like :S, but the rhs goes to the end of
   1767      *	    	    	    	the invocation.
   1768      */
   1769     if ((str != (char *)NULL) && haveModifier) {
   1770 	/*
   1771 	 * Skip initial colon while putting it back.
   1772 	 */
   1773 	*tstr++ = ':';
   1774 	while (*tstr != endc) {
   1775 	    char	*newStr;    /* New value to return */
   1776 	    char	termc;	    /* Character which terminated scan */
   1777 
   1778 	    if (DEBUG(VAR)) {
   1779 		printf("Applying :%c to \"%s\"\n", *tstr, str);
   1780 	    }
   1781 	    switch (*tstr) {
   1782 		case 'N':
   1783 		case 'M':
   1784 		{
   1785 		    char    *pattern;
   1786 		    char    *cp2;
   1787 		    Boolean copy;
   1788 
   1789 		    copy = FALSE;
   1790 		    for (cp = tstr + 1;
   1791 			 *cp != '\0' && *cp != ':' && *cp != endc;
   1792 			 cp++)
   1793 		    {
   1794 			if (*cp == '\\' && (cp[1] == ':' || cp[1] == endc)){
   1795 			    copy = TRUE;
   1796 			    cp++;
   1797 			}
   1798 		    }
   1799 		    termc = *cp;
   1800 		    *cp = '\0';
   1801 		    if (copy) {
   1802 			/*
   1803 			 * Need to compress the \:'s out of the pattern, so
   1804 			 * allocate enough room to hold the uncompressed
   1805 			 * pattern (note that cp started at tstr+1, so
   1806 			 * cp - tstr takes the null byte into account) and
   1807 			 * compress the pattern into the space.
   1808 			 */
   1809 			pattern = emalloc(cp - tstr);
   1810 			for (cp2 = pattern, cp = tstr + 1;
   1811 			     *cp != '\0';
   1812 			     cp++, cp2++)
   1813 			{
   1814 			    if ((*cp == '\\') &&
   1815 				(cp[1] == ':' || cp[1] == endc)) {
   1816 				    cp++;
   1817 			    }
   1818 			    *cp2 = *cp;
   1819 			}
   1820 			*cp2 = '\0';
   1821 		    } else {
   1822 			pattern = &tstr[1];
   1823 		    }
   1824 		    if (*tstr == 'M' || *tstr == 'm') {
   1825 			newStr = VarModify(str, VarMatch, (ClientData)pattern);
   1826 		    } else {
   1827 			newStr = VarModify(str, VarNoMatch,
   1828 					   (ClientData)pattern);
   1829 		    }
   1830 		    if (copy) {
   1831 			free(pattern);
   1832 		    }
   1833 		    break;
   1834 		}
   1835 		case 'S':
   1836 		{
   1837 		    VarPattern 	    pattern;
   1838 
   1839 		    pattern.flags = 0;
   1840 		    delim = tstr[1];
   1841 		    tstr += 2;
   1842 
   1843 		    /*
   1844 		     * If pattern begins with '^', it is anchored to the
   1845 		     * start of the word -- skip over it and flag pattern.
   1846 		     */
   1847 		    if (*tstr == '^') {
   1848 			pattern.flags |= VAR_MATCH_START;
   1849 			tstr += 1;
   1850 		    }
   1851 
   1852 		    cp = tstr;
   1853 		    if ((pattern.lhs = VarGetPattern(ctxt, err, &cp, delim,
   1854 			&pattern.flags, &pattern.leftLen, NULL)) == NULL)
   1855 			goto cleanup;
   1856 
   1857 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
   1858 			NULL, &pattern.rightLen, &pattern)) == NULL)
   1859 			goto cleanup;
   1860 
   1861 		    /*
   1862 		     * Check for global substitution. If 'g' after the final
   1863 		     * delimiter, substitution is global and is marked that
   1864 		     * way.
   1865 		     */
   1866 		    for (;; cp++) {
   1867 			switch (*cp) {
   1868 			case 'g':
   1869 			    pattern.flags |= VAR_SUB_GLOBAL;
   1870 			    continue;
   1871 			case '1':
   1872 			    pattern.flags |= VAR_SUB_ONE;
   1873 			    continue;
   1874 			}
   1875 			break;
   1876 		    }
   1877 
   1878 		    termc = *cp;
   1879 		    newStr = VarModify(str, VarSubstitute,
   1880 				       (ClientData)&pattern);
   1881 
   1882 		    /*
   1883 		     * Free the two strings.
   1884 		     */
   1885 		    free(pattern.lhs);
   1886 		    free(pattern.rhs);
   1887 		    break;
   1888 		}
   1889 		case '?':
   1890 		{
   1891 		    VarPattern 	pattern;
   1892 		    Boolean	value;
   1893 
   1894 		    /* find ':', and then substitute accordingly */
   1895 
   1896 		    pattern.flags = 0;
   1897 
   1898 		    cp = ++tstr;
   1899 		    delim = ':';
   1900 		    if ((pattern.lhs = VarGetPattern(ctxt, err, &cp, delim,
   1901 			NULL, &pattern.leftLen, NULL)) == NULL)
   1902 			goto cleanup;
   1903 
   1904 		    delim = '}';
   1905 		    if ((pattern.rhs = VarGetPattern(ctxt, err, &cp, delim,
   1906 			NULL, &pattern.rightLen, NULL)) == NULL)
   1907 			goto cleanup;
   1908 
   1909 		    termc = *--cp;
   1910 		    delim = '\0';
   1911 		    if (Cond_EvalExpression(1, str, &value, 0) == COND_INVALID){
   1912 			Error("Bad conditional expression `%s' in %s?%s:%s",
   1913 			      str, str, pattern.lhs, pattern.rhs);
   1914 			goto cleanup;
   1915 		    }
   1916 
   1917 		    if (value) {
   1918 			newStr = pattern.lhs;
   1919 			free(pattern.rhs);
   1920 		    } else {
   1921 			newStr = pattern.rhs;
   1922 			free(pattern.lhs);
   1923 		    }
   1924 		    break;
   1925 		}
   1926 #ifndef NO_REGEX
   1927 		case 'C':
   1928 		{
   1929 		    VarREPattern    pattern;
   1930 		    char           *re;
   1931 		    int             error;
   1932 
   1933 		    pattern.flags = 0;
   1934 		    delim = tstr[1];
   1935 		    tstr += 2;
   1936 
   1937 		    cp = tstr;
   1938 
   1939 		    if ((re = VarGetPattern(ctxt, err, &cp, delim, NULL,
   1940 			NULL, NULL)) == NULL)
   1941 			goto cleanup;
   1942 
   1943 		    if ((pattern.replace = VarGetPattern(ctxt, err, &cp,
   1944 			delim, NULL, NULL, NULL)) == NULL){
   1945 			free(re);
   1946 			goto cleanup;
   1947 		    }
   1948 
   1949 		    for (;; cp++) {
   1950 			switch (*cp) {
   1951 			case 'g':
   1952 			    pattern.flags |= VAR_SUB_GLOBAL;
   1953 			    continue;
   1954 			case '1':
   1955 			    pattern.flags |= VAR_SUB_ONE;
   1956 			    continue;
   1957 			}
   1958 			break;
   1959 		    }
   1960 
   1961 		    termc = *cp;
   1962 
   1963 		    error = regcomp(&pattern.re, re, REG_EXTENDED);
   1964 		    free(re);
   1965 		    if (error)  {
   1966 			*lengthPtr = cp - start + 1;
   1967 			VarREError(error, &pattern.re, "RE substitution error");
   1968 			free(pattern.replace);
   1969 			return (var_Error);
   1970 		    }
   1971 
   1972 		    pattern.nsub = pattern.re.re_nsub + 1;
   1973 		    if (pattern.nsub < 1)
   1974 			pattern.nsub = 1;
   1975 		    if (pattern.nsub > 10)
   1976 			pattern.nsub = 10;
   1977 		    pattern.matches = emalloc(pattern.nsub *
   1978 					      sizeof(regmatch_t));
   1979 		    newStr = VarModify(str, VarRESubstitute,
   1980 				       (ClientData) &pattern);
   1981 		    regfree(&pattern.re);
   1982 		    free(pattern.replace);
   1983 		    free(pattern.matches);
   1984 		    break;
   1985 		}
   1986 #endif
   1987 		case 'Q':
   1988 		    if (tstr[1] == endc || tstr[1] == ':') {
   1989 			newStr = VarQuote (str);
   1990 			cp = tstr + 1;
   1991 			termc = *cp;
   1992 			break;
   1993 		    }
   1994 		    /*FALLTHRU*/
   1995 		case 'T':
   1996 		    if (tstr[1] == endc || tstr[1] == ':') {
   1997 			newStr = VarModify (str, VarTail, (ClientData)0);
   1998 			cp = tstr + 1;
   1999 			termc = *cp;
   2000 			break;
   2001 		    }
   2002 		    /*FALLTHRU*/
   2003 		case 'H':
   2004 		    if (tstr[1] == endc || tstr[1] == ':') {
   2005 			newStr = VarModify (str, VarHead, (ClientData)0);
   2006 			cp = tstr + 1;
   2007 			termc = *cp;
   2008 			break;
   2009 		    }
   2010 		    /*FALLTHRU*/
   2011 		case 'E':
   2012 		    if (tstr[1] == endc || tstr[1] == ':') {
   2013 			newStr = VarModify (str, VarSuffix, (ClientData)0);
   2014 			cp = tstr + 1;
   2015 			termc = *cp;
   2016 			break;
   2017 		    }
   2018 		    /*FALLTHRU*/
   2019 		case 'R':
   2020 		    if (tstr[1] == endc || tstr[1] == ':') {
   2021 			newStr = VarModify (str, VarRoot, (ClientData)0);
   2022 			cp = tstr + 1;
   2023 			termc = *cp;
   2024 			break;
   2025 		    }
   2026 		    /*FALLTHRU*/
   2027 		case 'O':
   2028 		    if (tstr[1] == endc || tstr[1] == ':') {
   2029 			newStr = VarSort (str);
   2030 			cp = tstr + 1;
   2031 			termc = *cp;
   2032 			break;
   2033 		    }
   2034 #ifdef SUNSHCMD
   2035 		case 's':
   2036 		    if (tstr[1] == 'h' && (tstr[2] == endc || tstr[2] == ':')) {
   2037 			char *err;
   2038 			newStr = Cmd_Exec (str, &err);
   2039 			if (err)
   2040 			    Error (err, str);
   2041 			cp = tstr + 2;
   2042 			termc = *cp;
   2043 			break;
   2044 		    }
   2045 		    /*FALLTHRU*/
   2046 #endif
   2047 		default:
   2048 		{
   2049 #ifdef SYSVVARSUB
   2050 		    /*
   2051 		     * This can either be a bogus modifier or a System-V
   2052 		     * substitution command.
   2053 		     */
   2054 		    VarPattern      pattern;
   2055 		    Boolean         eqFound;
   2056 
   2057 		    pattern.flags = 0;
   2058 		    eqFound = FALSE;
   2059 		    /*
   2060 		     * First we make a pass through the string trying
   2061 		     * to verify it is a SYSV-make-style translation:
   2062 		     * it must be: <string1>=<string2>)
   2063 		     */
   2064 		    cp = tstr;
   2065 		    cnt = 1;
   2066 		    while (*cp != '\0' && cnt) {
   2067 			if (*cp == '=') {
   2068 			    eqFound = TRUE;
   2069 			    /* continue looking for endc */
   2070 			}
   2071 			else if (*cp == endc)
   2072 			    cnt--;
   2073 			else if (*cp == startc)
   2074 			    cnt++;
   2075 			if (cnt)
   2076 			    cp++;
   2077 		    }
   2078 		    if (*cp == endc && eqFound) {
   2079 
   2080 			/*
   2081 			 * Now we break this sucker into the lhs and
   2082 			 * rhs. We must null terminate them of course.
   2083 			 */
   2084 			for (cp = tstr; *cp != '='; cp++)
   2085 			    continue;
   2086 			pattern.lhs = tstr;
   2087 			pattern.leftLen = cp - tstr;
   2088 			*cp++ = '\0';
   2089 
   2090 			pattern.rhs = cp;
   2091 			cnt = 1;
   2092 			while (cnt) {
   2093 			    if (*cp == endc)
   2094 				cnt--;
   2095 			    else if (*cp == startc)
   2096 				cnt++;
   2097 			    if (cnt)
   2098 				cp++;
   2099 			}
   2100 			pattern.rightLen = cp - pattern.rhs;
   2101 			*cp = '\0';
   2102 
   2103 			/*
   2104 			 * SYSV modifications happen through the whole
   2105 			 * string. Note the pattern is anchored at the end.
   2106 			 */
   2107 			newStr = VarModify(str, VarSYSVMatch,
   2108 					   (ClientData)&pattern);
   2109 
   2110 			/*
   2111 			 * Restore the nulled characters
   2112 			 */
   2113 			pattern.lhs[pattern.leftLen] = '=';
   2114 			pattern.rhs[pattern.rightLen] = endc;
   2115 			termc = endc;
   2116 		    } else
   2117 #endif
   2118 		    {
   2119 			Error ("Unknown modifier '%c'\n", *tstr);
   2120 			for (cp = tstr+1;
   2121 			     *cp != ':' && *cp != endc && *cp != '\0';
   2122 			     cp++)
   2123 				 continue;
   2124 			termc = *cp;
   2125 			newStr = var_Error;
   2126 		    }
   2127 		}
   2128 	    }
   2129 	    if (DEBUG(VAR)) {
   2130 		printf("Result is \"%s\"\n", newStr);
   2131 	    }
   2132 
   2133 	    if (*freePtr) {
   2134 		free (str);
   2135 	    }
   2136 	    str = newStr;
   2137 	    if (str != var_Error) {
   2138 		*freePtr = TRUE;
   2139 	    } else {
   2140 		*freePtr = FALSE;
   2141 	    }
   2142 	    if (termc == '\0') {
   2143 		Error("Unclosed variable specification for %s", v->name);
   2144 	    } else if (termc == ':') {
   2145 		*cp++ = termc;
   2146 	    } else {
   2147 		*cp = termc;
   2148 	    }
   2149 	    tstr = cp;
   2150 	}
   2151 	*lengthPtr = tstr - start + 1;
   2152     } else {
   2153 	*lengthPtr = tstr - start + 1;
   2154 	*tstr = endc;
   2155     }
   2156 
   2157     if (v->flags & VAR_FROM_ENV) {
   2158 	Boolean	  destroy = FALSE;
   2159 
   2160 	if (str != (char *)Buf_GetAll(v->val, (int *)NULL)) {
   2161 	    destroy = TRUE;
   2162 	} else {
   2163 	    /*
   2164 	     * Returning the value unmodified, so tell the caller to free
   2165 	     * the thing.
   2166 	     */
   2167 	    *freePtr = TRUE;
   2168 	}
   2169 	free(v->name);
   2170 	Buf_Destroy(v->val, destroy);
   2171 	free((Address)v);
   2172     } else if (v->flags & VAR_JUNK) {
   2173 	/*
   2174 	 * Perform any free'ing needed and set *freePtr to FALSE so the caller
   2175 	 * doesn't try to free a static pointer.
   2176 	 */
   2177 	if (*freePtr) {
   2178 	    free(str);
   2179 	}
   2180 	*freePtr = FALSE;
   2181 	Buf_Destroy(v->val, TRUE);
   2182 	free((Address)v);
   2183 	if (dynamic) {
   2184 	    str = emalloc(*lengthPtr + 1);
   2185 	    strncpy(str, start, *lengthPtr);
   2186 	    str[*lengthPtr] = '\0';
   2187 	    *freePtr = TRUE;
   2188 	} else {
   2189 	    str = var_Error;
   2190 	}
   2191     }
   2192     return (str);
   2193 
   2194 cleanup:
   2195     *lengthPtr = cp - start + 1;
   2196     if (*freePtr)
   2197 	free(str);
   2198     if (delim != '\0')
   2199 	Error("Unclosed substitution for %s (%c missing)",
   2200 	      v->name, delim);
   2201     return (var_Error);
   2202 }
   2203 
   2204 /*-
   2205  *-----------------------------------------------------------------------
   2206  * Var_Subst  --
   2207  *	Substitute for all variables in the given string in the given context
   2208  *	If undefErr is TRUE, Parse_Error will be called when an undefined
   2209  *	variable is encountered.
   2210  *
   2211  * Results:
   2212  *	The resulting string.
   2213  *
   2214  * Side Effects:
   2215  *	None. The old string must be freed by the caller
   2216  *-----------------------------------------------------------------------
   2217  */
   2218 char *
   2219 Var_Subst (var, str, ctxt, undefErr)
   2220     char	  *var;		    /* Named variable || NULL for all */
   2221     char 	  *str;	    	    /* the string in which to substitute */
   2222     GNode         *ctxt;	    /* the context wherein to find variables */
   2223     Boolean 	  undefErr; 	    /* TRUE if undefineds are an error */
   2224 {
   2225     Buffer  	  buf;	    	    /* Buffer for forming things */
   2226     char    	  *val;		    /* Value to substitute for a variable */
   2227     int	    	  length;   	    /* Length of the variable invocation */
   2228     Boolean 	  doFree;   	    /* Set true if val should be freed */
   2229     static Boolean errorReported;   /* Set true if an error has already
   2230 				     * been reported to prevent a plethora
   2231 				     * of messages when recursing */
   2232 
   2233     buf = Buf_Init (MAKE_BSIZE);
   2234     errorReported = FALSE;
   2235 
   2236     while (*str) {
   2237 	if (var == NULL && (*str == '$') && (str[1] == '$')) {
   2238 	    /*
   2239 	     * A dollar sign may be escaped either with another dollar sign.
   2240 	     * In such a case, we skip over the escape character and store the
   2241 	     * dollar sign into the buffer directly.
   2242 	     */
   2243 	    str++;
   2244 	    Buf_AddByte(buf, (Byte)*str);
   2245 	    str++;
   2246 	} else if (*str != '$') {
   2247 	    /*
   2248 	     * Skip as many characters as possible -- either to the end of
   2249 	     * the string or to the next dollar sign (variable invocation).
   2250 	     */
   2251 	    char  *cp;
   2252 
   2253 	    for (cp = str++; *str != '$' && *str != '\0'; str++)
   2254 		continue;
   2255 	    Buf_AddBytes(buf, str - cp, (Byte *)cp);
   2256 	} else {
   2257 	    if (var != NULL) {
   2258 		int expand;
   2259 		for (;;) {
   2260 		    if (str[1] != '(' && str[1] != '{') {
   2261 			if (str[1] != *var) {
   2262 			    Buf_AddBytes(buf, 2, (Byte *) str);
   2263 			    str += 2;
   2264 			    expand = FALSE;
   2265 			}
   2266 			else
   2267 			    expand = TRUE;
   2268 			break;
   2269 		    }
   2270 		    else {
   2271 			char *p;
   2272 
   2273 			/*
   2274 			 * Scan up to the end of the variable name.
   2275 			 */
   2276 			for (p = &str[2]; *p &&
   2277 			     *p != ':' && *p != ')' && *p != '}'; p++)
   2278 			    if (*p == '$')
   2279 				break;
   2280 			/*
   2281 			 * A variable inside the variable. We cannot expand
   2282 			 * the external variable yet, so we try again with
   2283 			 * the nested one
   2284 			 */
   2285 			if (*p == '$') {
   2286 			    Buf_AddBytes(buf, p - str, (Byte *) str);
   2287 			    str = p;
   2288 			    continue;
   2289 			}
   2290 
   2291 			if (strncmp(var, str + 2, p - str - 2) != 0 ||
   2292 			    var[p - str - 2] != '\0') {
   2293 			    /*
   2294 			     * Not the variable we want to expand, scan
   2295 			     * until the next variable
   2296 			     */
   2297 			    for (;*p != '$' && *p != '\0'; p++)
   2298 				continue;
   2299 			    Buf_AddBytes(buf, p - str, (Byte *) str);
   2300 			    str = p;
   2301 			    expand = FALSE;
   2302 			}
   2303 			else
   2304 			    expand = TRUE;
   2305 			break;
   2306 		    }
   2307 		}
   2308 		if (!expand)
   2309 		    continue;
   2310 	    }
   2311 
   2312 	    val = Var_Parse (str, ctxt, undefErr, &length, &doFree);
   2313 
   2314 	    /*
   2315 	     * When we come down here, val should either point to the
   2316 	     * value of this variable, suitably modified, or be NULL.
   2317 	     * Length should be the total length of the potential
   2318 	     * variable invocation (from $ to end character...)
   2319 	     */
   2320 	    if (val == var_Error || val == varNoError) {
   2321 		/*
   2322 		 * If performing old-time variable substitution, skip over
   2323 		 * the variable and continue with the substitution. Otherwise,
   2324 		 * store the dollar sign and advance str so we continue with
   2325 		 * the string...
   2326 		 */
   2327 		if (oldVars) {
   2328 		    str += length;
   2329 		} else if (undefErr) {
   2330 		    /*
   2331 		     * If variable is undefined, complain and skip the
   2332 		     * variable. The complaint will stop us from doing anything
   2333 		     * when the file is parsed.
   2334 		     */
   2335 		    if (!errorReported) {
   2336 			Parse_Error (PARSE_FATAL,
   2337 				     "Undefined variable \"%.*s\"",length,str);
   2338 		    }
   2339 		    str += length;
   2340 		    errorReported = TRUE;
   2341 		} else {
   2342 		    Buf_AddByte (buf, (Byte)*str);
   2343 		    str += 1;
   2344 		}
   2345 	    } else {
   2346 		/*
   2347 		 * We've now got a variable structure to store in. But first,
   2348 		 * advance the string pointer.
   2349 		 */
   2350 		str += length;
   2351 
   2352 		/*
   2353 		 * Copy all the characters from the variable value straight
   2354 		 * into the new string.
   2355 		 */
   2356 		Buf_AddBytes (buf, strlen (val), (Byte *)val);
   2357 		if (doFree) {
   2358 		    free ((Address)val);
   2359 		}
   2360 	    }
   2361 	}
   2362     }
   2363 
   2364     Buf_AddByte (buf, '\0');
   2365     str = (char *)Buf_GetAll (buf, (int *)NULL);
   2366     Buf_Destroy (buf, FALSE);
   2367     return (str);
   2368 }
   2369 
   2370 /*-
   2371  *-----------------------------------------------------------------------
   2372  * Var_GetTail --
   2373  *	Return the tail from each of a list of words. Used to set the
   2374  *	System V local variables.
   2375  *
   2376  * Results:
   2377  *	The resulting string.
   2378  *
   2379  * Side Effects:
   2380  *	None.
   2381  *
   2382  *-----------------------------------------------------------------------
   2383  */
   2384 char *
   2385 Var_GetTail(file)
   2386     char    	*file;	    /* Filename to modify */
   2387 {
   2388     return(VarModify(file, VarTail, (ClientData)0));
   2389 }
   2390 
   2391 /*-
   2392  *-----------------------------------------------------------------------
   2393  * Var_GetHead --
   2394  *	Find the leading components of a (list of) filename(s).
   2395  *	XXX: VarHead does not replace foo by ., as (sun) System V make
   2396  *	does.
   2397  *
   2398  * Results:
   2399  *	The leading components.
   2400  *
   2401  * Side Effects:
   2402  *	None.
   2403  *
   2404  *-----------------------------------------------------------------------
   2405  */
   2406 char *
   2407 Var_GetHead(file)
   2408     char    	*file;	    /* Filename to manipulate */
   2409 {
   2410     return(VarModify(file, VarHead, (ClientData)0));
   2411 }
   2412 
   2413 /*-
   2414  *-----------------------------------------------------------------------
   2415  * Var_Init --
   2416  *	Initialize the module
   2417  *
   2418  * Results:
   2419  *	None
   2420  *
   2421  * Side Effects:
   2422  *	The VAR_CMD and VAR_GLOBAL contexts are created
   2423  *-----------------------------------------------------------------------
   2424  */
   2425 void
   2426 Var_Init ()
   2427 {
   2428     VAR_GLOBAL = Targ_NewGN ("Global");
   2429     VAR_CMD = Targ_NewGN ("Command");
   2430 
   2431 }
   2432 
   2433 
   2434 void
   2435 Var_End ()
   2436 {
   2437 }
   2438 
   2439 
   2440 /****************** PRINT DEBUGGING INFO *****************/
   2441 static void
   2442 VarPrintVar (vp)
   2443     ClientData vp;
   2444 {
   2445     Var    *v = (Var *) vp;
   2446     printf ("%-16s = %s\n", v->name, (char *) Buf_GetAll(v->val, (int *)NULL));
   2447 }
   2448 
   2449 /*-
   2450  *-----------------------------------------------------------------------
   2451  * Var_Dump --
   2452  *	print all variables in a context
   2453  *-----------------------------------------------------------------------
   2454  */
   2455 void
   2456 Var_Dump (ctxt)
   2457     GNode          *ctxt;
   2458 {
   2459     Hash_Search search;
   2460     Hash_Entry *h;
   2461 
   2462     for (h = Hash_EnumFirst(&ctxt->context, &search);
   2463 	 h != NULL;
   2464 	 h = Hash_EnumNext(&search)) {
   2465 	    VarPrintVar(Hash_GetValue(h));
   2466     }
   2467 }
   2468