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