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