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