Home | History | Annotate | Line # | Download | only in make
var.c revision 1.443
      1 /*	$NetBSD: var.c,v 1.443 2020/08/09 14:02:15 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.443 2020/08/09 14:02:15 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.443 2020/08/09 14:02:15 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 	    } else if (*rp == '&' ||
   1388 		       (*rp == '\\' && isdigit((unsigned char)rp[1]))) {
   1389 		int n;
   1390 		char errstr[3];
   1391 
   1392 		if (*rp == '&') {
   1393 		    n = 0;
   1394 		    errstr[0] = '&';
   1395 		    errstr[1] = '\0';
   1396 		} else {
   1397 		    n = rp[1] - '0';
   1398 		    errstr[0] = '\\';
   1399 		    errstr[1] = rp[1];
   1400 		    errstr[2] = '\0';
   1401 		    rp++;
   1402 		}
   1403 
   1404 		if (n >= args->nsub) {
   1405 		    Error("No subexpression %s", errstr);
   1406 		} else if (m[n].rm_so == -1 && m[n].rm_eo == -1) {
   1407 		    Error("No match for subexpression %s", errstr);
   1408 		} else {
   1409 		    SepBuf_AddBytesBetween(buf, wp + m[n].rm_so,
   1410 					   wp + m[n].rm_eo);
   1411 		}
   1412 
   1413 	    } else {
   1414 		SepBuf_AddBytes(buf, rp, 1);
   1415 	    }
   1416 	}
   1417 	wp += m[0].rm_eo;
   1418 	if (args->pflags & VARP_SUB_GLOBAL) {
   1419 	    flags |= REG_NOTBOL;
   1420 	    if (m[0].rm_so == 0 && m[0].rm_eo == 0) {
   1421 		SepBuf_AddBytes(buf, wp, 1);
   1422 		wp++;
   1423 	    }
   1424 	    if (*wp)
   1425 		goto tryagain;
   1426 	}
   1427 	if (*wp) {
   1428 	    SepBuf_AddStr(buf, wp);
   1429 	}
   1430 	break;
   1431     default:
   1432 	VarREError(xrv, &args->re, "Unexpected regex error");
   1433 	/* fall through */
   1434     case REG_NOMATCH:
   1435     nosub:
   1436 	SepBuf_AddStr(buf, wp);
   1437 	break;
   1438     }
   1439 }
   1440 #endif
   1441 
   1442 
   1443 typedef struct {
   1444     GNode	*ctx;
   1445     char	*tvar;		/* name of temporary variable */
   1446     char	*str;		/* string to expand */
   1447     VarEvalFlags eflags;
   1448 } ModifyWord_LoopArgs;
   1449 
   1450 /* Callback for ModifyWords to implement the :@var (at) ...@ modifier of ODE make. */
   1451 static void
   1452 ModifyWord_Loop(const char *word, SepBuf *buf, void *data)
   1453 {
   1454     const ModifyWord_LoopArgs *args;
   1455     char *s;
   1456 
   1457     if (word[0] == '\0')
   1458 	return;
   1459 
   1460     args = data;
   1461     Var_Set_with_flags(args->tvar, word, args->ctx, VAR_NO_EXPORT);
   1462     s = Var_Subst(args->str, args->ctx, args->eflags);
   1463 
   1464     VAR_DEBUG("ModifyWord_Loop: in \"%s\", replace \"%s\" with \"%s\" "
   1465 	      "to \"%s\"\n",
   1466 	      word, args->tvar, args->str, s ? s : "(null)");
   1467 
   1468     if (s != NULL && s[0] != '\0') {
   1469 	if (s[0] == '\n' || (buf->buf.count > 0 &&
   1470 			     buf->buf.buffer[buf->buf.count - 1] == '\n'))
   1471 	    buf->needSep = FALSE;
   1472 	SepBuf_AddStr(buf, s);
   1473     }
   1474     free(s);
   1475 }
   1476 
   1477 
   1478 /*-
   1479  * Implements the :[first..last] modifier.
   1480  * This is a special case of ModifyWords since we want to be able
   1481  * to scan the list backwards if first > last.
   1482  */
   1483 static char *
   1484 VarSelectWords(Byte sep, Boolean oneBigWord, const char *str, int first,
   1485 	       int last)
   1486 {
   1487     char **av;			/* word list */
   1488     char *as;			/* word list memory */
   1489     int ac;
   1490     int start, end, step;
   1491     int i;
   1492 
   1493     SepBuf buf;
   1494     SepBuf_Init(&buf, sep);
   1495 
   1496     if (oneBigWord) {
   1497 	/* fake what brk_string() would do if there were only one word */
   1498 	ac = 1;
   1499 	av = bmake_malloc((ac + 1) * sizeof(char *));
   1500 	as = bmake_strdup(str);
   1501 	av[0] = as;
   1502 	av[1] = NULL;
   1503     } else {
   1504 	av = brk_string(str, &ac, FALSE, &as);
   1505     }
   1506 
   1507     /*
   1508      * Now sanitize the given range.
   1509      * If first or last are negative, convert them to the positive equivalents
   1510      * (-1 gets converted to ac, -2 gets converted to (ac - 1), etc.).
   1511      */
   1512     if (first < 0)
   1513 	first += ac + 1;
   1514     if (last < 0)
   1515 	last += ac + 1;
   1516 
   1517     /*
   1518      * We avoid scanning more of the list than we need to.
   1519      */
   1520     if (first > last) {
   1521 	start = MIN(ac, first) - 1;
   1522 	end = MAX(0, last - 1);
   1523 	step = -1;
   1524     } else {
   1525 	start = MAX(0, first - 1);
   1526 	end = MIN(ac, last);
   1527 	step = 1;
   1528     }
   1529 
   1530     for (i = start; (step < 0) == (i >= end); i += step) {
   1531 	SepBuf_AddStr(&buf, av[i]);
   1532 	SepBuf_Sep(&buf);
   1533     }
   1534 
   1535     free(as);
   1536     free(av);
   1537 
   1538     return SepBuf_Destroy(&buf, FALSE);
   1539 }
   1540 
   1541 
   1542 /* Callback for ModifyWords to implement the :tA modifier.
   1543  * Replace each word with the result of realpath() if successful. */
   1544 static void
   1545 ModifyWord_Realpath(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   1546 {
   1547     struct stat st;
   1548     char rbuf[MAXPATHLEN];
   1549 
   1550     const char *rp = cached_realpath(word, rbuf);
   1551     if (rp != NULL && *rp == '/' && stat(rp, &st) == 0)
   1552 	word = rp;
   1553 
   1554     SepBuf_AddStr(buf, word);
   1555 }
   1556 
   1557 /*-
   1558  *-----------------------------------------------------------------------
   1559  * Modify each of the words of the passed string using the given function.
   1560  *
   1561  * Input:
   1562  *	str		String whose words should be modified
   1563  *	modifyWord	Function that modifies a single word
   1564  *	data		Custom data for modifyWord
   1565  *
   1566  * Results:
   1567  *	A string of all the words modified appropriately.
   1568  *-----------------------------------------------------------------------
   1569  */
   1570 static char *
   1571 ModifyWords(GNode *ctx, Byte sep, Boolean oneBigWord,
   1572 	    const char *str, ModifyWordsCallback modifyWord, void *data)
   1573 {
   1574     SepBuf result;
   1575     char **av;			/* word list */
   1576     char *as;			/* word list memory */
   1577     int ac;
   1578     int i;
   1579 
   1580     if (oneBigWord) {
   1581 	SepBuf_Init(&result, sep);
   1582 	modifyWord(str, &result, data);
   1583 	return SepBuf_Destroy(&result, FALSE);
   1584     }
   1585 
   1586     SepBuf_Init(&result, sep);
   1587 
   1588     av = brk_string(str, &ac, FALSE, &as);
   1589 
   1590     VAR_DEBUG("ModifyWords: split \"%s\" into %d words\n", str, ac);
   1591 
   1592     for (i = 0; i < ac; i++) {
   1593 	modifyWord(av[i], &result, data);
   1594 	if (result.buf.count > 0)
   1595 	    SepBuf_Sep(&result);
   1596     }
   1597 
   1598     free(as);
   1599     free(av);
   1600 
   1601     return SepBuf_Destroy(&result, FALSE);
   1602 }
   1603 
   1604 
   1605 static char *
   1606 WordList_JoinFree(char **av, int ac, char *as)
   1607 {
   1608     Buffer buf;
   1609     int i;
   1610 
   1611     Buf_Init(&buf, 0);
   1612 
   1613     for (i = 0; i < ac; i++) {
   1614 	if (i != 0)
   1615 	    Buf_AddByte(&buf, ' ');	/* XXX: st->sep, for consistency */
   1616 	Buf_AddStr(&buf, av[i]);
   1617     }
   1618 
   1619     free(av);
   1620     free(as);
   1621 
   1622     return Buf_Destroy(&buf, FALSE);
   1623 }
   1624 
   1625 /* Remove adjacent duplicate words. */
   1626 static char *
   1627 VarUniq(const char *str)
   1628 {
   1629     char *as;			/* Word list memory */
   1630     int ac;
   1631     char **av = brk_string(str, &ac, FALSE, &as);
   1632 
   1633     if (ac > 1) {
   1634 	int i, j;
   1635 	for (j = 0, i = 1; i < ac; i++)
   1636 	    if (strcmp(av[i], av[j]) != 0 && (++j != i))
   1637 		av[j] = av[i];
   1638 	ac = j + 1;
   1639     }
   1640 
   1641     return WordList_JoinFree(av, ac, as);
   1642 }
   1643 
   1644 
   1645 /*-
   1646  * Parse a text part of a modifier such as the "from" and "to" in :S/from/to/
   1647  * or the :@ modifier, until the next unescaped delimiter.  The delimiter, as
   1648  * well as the backslash or the dollar, can be escaped with a backslash.
   1649  *
   1650  * Return the parsed (and possibly expanded) string, or NULL if no delimiter
   1651  * was found.  On successful return, the parsing position pp points right
   1652  * after the delimiter.  The delimiter is not included in the returned
   1653  * value though.
   1654  */
   1655 static char *
   1656 ParseModifierPart(
   1657     const char **pp,		/* The parsing position, updated upon return */
   1658     int delim,			/* Parsing stops at this delimiter */
   1659     VarEvalFlags eflags,	/* Flags for evaluating nested variables;
   1660 				 * if VARE_WANTRES is not set, the text is
   1661 				 * only parsed */
   1662     GNode *ctxt,		/* For looking up nested variables */
   1663     size_t *out_length,		/* Optionally stores the length of the returned
   1664 				 * string, just to save another strlen call. */
   1665     VarPatternFlags *out_pflags,/* For the first part of the :S modifier,
   1666 				 * sets the VARP_ANCHOR_END flag if the last
   1667 				 * character of the pattern is a $. */
   1668     ModifyWord_SubstArgs *subst	/* For the second part of the :S modifier,
   1669 				 * allow ampersands to be escaped and replace
   1670 				 * unescaped ampersands with subst->lhs. */
   1671 ) {
   1672     Buffer buf;
   1673     const char *p;
   1674     char *rstr;
   1675 
   1676     Buf_Init(&buf, 0);
   1677 
   1678     /*
   1679      * Skim through until the matching delimiter is found;
   1680      * pick up variable substitutions on the way. Also allow
   1681      * backslashes to quote the delimiter, $, and \, but don't
   1682      * touch other backslashes.
   1683      */
   1684     p = *pp;
   1685     while (*p != '\0' && *p != delim) {
   1686 	const char *varstart;
   1687 
   1688 	Boolean is_escaped = p[0] == '\\' && (
   1689 	    p[1] == delim || p[1] == '\\' || p[1] == '$' ||
   1690 	    (p[1] == '&' && subst != NULL));
   1691 	if (is_escaped) {
   1692 	    Buf_AddByte(&buf, p[1]);
   1693 	    p += 2;
   1694 	    continue;
   1695 	}
   1696 
   1697 	if (*p != '$') {	/* Unescaped, simple text */
   1698 	    if (subst != NULL && *p == '&')
   1699 		Buf_AddBytes(&buf, subst->lhs, subst->lhsLen);
   1700 	    else
   1701 		Buf_AddByte(&buf, *p);
   1702 	    p++;
   1703 	    continue;
   1704 	}
   1705 
   1706 	if (p[1] == delim) {	/* Unescaped $ at end of pattern */
   1707 	    if (out_pflags != NULL)
   1708 		*out_pflags |= VARP_ANCHOR_END;
   1709 	    else
   1710 		Buf_AddByte(&buf, *p);
   1711 	    p++;
   1712 	    continue;
   1713 	}
   1714 
   1715 	if (eflags & VARE_WANTRES) {	/* Nested variable, evaluated */
   1716 	    const char *cp2;
   1717 	    int len;
   1718 	    void *freeIt;
   1719 
   1720 	    cp2 = Var_Parse(p, ctxt, eflags & ~VARE_ASSIGN, &len, &freeIt);
   1721 	    Buf_AddStr(&buf, cp2);
   1722 	    free(freeIt);
   1723 	    p += len;
   1724 	    continue;
   1725 	}
   1726 
   1727 	/* XXX: This whole block is very similar to Var_Parse without
   1728 	 * VARE_WANTRES.  There may be subtle edge cases though that are
   1729 	 * not yet covered in the unit tests and that are parsed differently,
   1730 	 * depending on whether they are evaluated or not.
   1731 	 *
   1732 	 * This subtle difference is not documented in the manual page,
   1733 	 * neither is the difference between parsing :D and :M documented.
   1734 	 * No code should ever depend on these details, but who knows. */
   1735 
   1736 	varstart = p;		/* Nested variable, only parsed */
   1737 	if (p[1] == PROPEN || p[1] == BROPEN) {
   1738 	    /*
   1739 	     * Find the end of this variable reference
   1740 	     * and suck it in without further ado.
   1741 	     * It will be interpreted later.
   1742 	     */
   1743 	    int have = p[1];
   1744 	    int want = have == PROPEN ? PRCLOSE : BRCLOSE;
   1745 	    int depth = 1;
   1746 
   1747 	    for (p += 2; *p != '\0' && depth > 0; p++) {
   1748 		if (p[-1] != '\\') {
   1749 		    if (*p == have)
   1750 			depth++;
   1751 		    if (*p == want)
   1752 			depth--;
   1753 		}
   1754 	    }
   1755 	    Buf_AddBytesBetween(&buf, varstart, p);
   1756 	} else {
   1757 	    Buf_AddByte(&buf, *varstart);
   1758 	    p++;
   1759 	}
   1760     }
   1761 
   1762     if (*p != delim) {
   1763 	*pp = p;
   1764 	return NULL;
   1765     }
   1766 
   1767     *pp = ++p;
   1768     if (out_length != NULL)
   1769 	*out_length = Buf_Size(&buf);
   1770 
   1771     rstr = Buf_Destroy(&buf, FALSE);
   1772     VAR_DEBUG("Modifier part: \"%s\"\n", rstr);
   1773     return rstr;
   1774 }
   1775 
   1776 /*-
   1777  *-----------------------------------------------------------------------
   1778  * VarQuote --
   1779  *	Quote shell meta-characters and space characters in the string
   1780  *	if quoteDollar is set, also quote and double any '$' characters.
   1781  *
   1782  * Results:
   1783  *	The quoted string
   1784  *
   1785  * Side Effects:
   1786  *	None.
   1787  *
   1788  *-----------------------------------------------------------------------
   1789  */
   1790 static char *
   1791 VarQuote(char *str, Boolean quoteDollar)
   1792 {
   1793     Buffer buf;
   1794     Buf_Init(&buf, 0);
   1795 
   1796     for (; *str != '\0'; str++) {
   1797 	if (*str == '\n') {
   1798 	    const char *newline = Shell_GetNewline();
   1799 	    if (newline == NULL)
   1800 		newline = "\\\n";
   1801 	    Buf_AddStr(&buf, newline);
   1802 	    continue;
   1803 	}
   1804 	if (isspace((unsigned char)*str) || ismeta((unsigned char)*str))
   1805 	    Buf_AddByte(&buf, '\\');
   1806 	Buf_AddByte(&buf, *str);
   1807 	if (quoteDollar && *str == '$')
   1808 	    Buf_AddStr(&buf, "\\$");
   1809     }
   1810 
   1811     str = Buf_Destroy(&buf, FALSE);
   1812     VAR_DEBUG("QuoteMeta: [%s]\n", str);
   1813     return str;
   1814 }
   1815 
   1816 /* Compute the 32-bit hash of the given string, using the MurmurHash3
   1817  * algorithm. Output is encoded as 8 hex digits, in Little Endian order. */
   1818 static char *
   1819 VarHash(const char *str)
   1820 {
   1821     static const char    hexdigits[16] = "0123456789abcdef";
   1822     const unsigned char *ustr = (const unsigned char *)str;
   1823 
   1824     uint32_t h  = 0x971e137bU;
   1825     uint32_t c1 = 0x95543787U;
   1826     uint32_t c2 = 0x2ad7eb25U;
   1827     size_t len2 = strlen(str);
   1828 
   1829     char *buf;
   1830     size_t i;
   1831 
   1832     size_t len;
   1833     for (len = len2; len; ) {
   1834 	uint32_t k = 0;
   1835 	switch (len) {
   1836 	default:
   1837 	    k = ((uint32_t)ustr[3] << 24) |
   1838 		((uint32_t)ustr[2] << 16) |
   1839 		((uint32_t)ustr[1] << 8) |
   1840 		(uint32_t)ustr[0];
   1841 	    len -= 4;
   1842 	    ustr += 4;
   1843 	    break;
   1844 	case 3:
   1845 	    k |= (uint32_t)ustr[2] << 16;
   1846 	    /* FALLTHROUGH */
   1847 	case 2:
   1848 	    k |= (uint32_t)ustr[1] << 8;
   1849 	    /* FALLTHROUGH */
   1850 	case 1:
   1851 	    k |= (uint32_t)ustr[0];
   1852 	    len = 0;
   1853 	}
   1854 	c1 = c1 * 5 + 0x7b7d159cU;
   1855 	c2 = c2 * 5 + 0x6bce6396U;
   1856 	k *= c1;
   1857 	k = (k << 11) ^ (k >> 21);
   1858 	k *= c2;
   1859 	h = (h << 13) ^ (h >> 19);
   1860 	h = h * 5 + 0x52dce729U;
   1861 	h ^= k;
   1862     }
   1863     h ^= len2;
   1864     h *= 0x85ebca6b;
   1865     h ^= h >> 13;
   1866     h *= 0xc2b2ae35;
   1867     h ^= h >> 16;
   1868 
   1869     buf = bmake_malloc(9);
   1870     for (i = 0; i < 8; i++) {
   1871 	buf[i] = hexdigits[h & 0x0f];
   1872 	h >>= 4;
   1873     }
   1874     buf[8] = '\0';
   1875     return buf;
   1876 }
   1877 
   1878 static char *
   1879 VarStrftime(const char *fmt, Boolean zulu, time_t tim)
   1880 {
   1881     char buf[BUFSIZ];
   1882 
   1883     if (!tim)
   1884 	time(&tim);
   1885     if (!*fmt)
   1886 	fmt = "%c";
   1887     strftime(buf, sizeof(buf), fmt, zulu ? gmtime(&tim) : localtime(&tim));
   1888 
   1889     buf[sizeof(buf) - 1] = '\0';
   1890     return bmake_strdup(buf);
   1891 }
   1892 
   1893 /* The ApplyModifier functions all work in the same way.  They get the
   1894  * current parsing position (pp) and parse the modifier from there.  The
   1895  * modifier typically lasts until the next ':', or a closing '}', ')'
   1896  * (taken from st->endc), or the end of the string (parse error).
   1897  *
   1898  * After parsing, no matter whether successful or not, they set the parsing
   1899  * position to the character after the modifier, or in case of parse errors,
   1900  * just increment the parsing position.  (That's how it is right now, it
   1901  * shouldn't hurt to keep the parsing position as-is in case of parse errors.)
   1902  *
   1903  * On success, an ApplyModifier function:
   1904  *	* sets the parsing position *pp to the first character following the
   1905  *	  current modifier
   1906  *	* processes the current variable value from st->val to produce the
   1907  *	  modified variable value and stores it in st->newVal
   1908  *	* returns AMR_OK
   1909  *
   1910  * On parse errors, an ApplyModifier function:
   1911  *	* either issues a custom error message and then returns AMR_CLEANUP
   1912  *	* or returns AMR_BAD to issue the standard "Bad modifier" error message
   1913  *	In both of these cases, it updates the parsing position.
   1914  *	Modifiers that use ParseModifierPart typically set st->missing_delim
   1915  *	and then return AMR_CLEANUP to issue the standard error message.
   1916  *
   1917  * If the expected modifier was not found, several modifiers return AMR_UNKNOWN
   1918  * to fall back to the SysV modifier ${VAR:from=to}.  This is especially
   1919  * useful for newly added long-name modifiers, to avoid breaking any existing
   1920  * code.  In such a case the parsing position must not be changed.
   1921  */
   1922 
   1923 typedef struct {
   1924     const char startc;		/* '\0' or '{' or '(' */
   1925     const char endc;		/* '\0' or '}' or ')' */
   1926     Var * const v;
   1927     GNode * const ctxt;
   1928     const VarEvalFlags eflags;
   1929 
   1930     char *val;			/* The value of the expression before the
   1931 				 * modifier is applied */
   1932     char *newVal;		/* The new value after applying the modifier
   1933 				 * to the expression */
   1934     char missing_delim;		/* For error reporting */
   1935 
   1936     Byte sep;			/* Word separator in expansions */
   1937     Boolean oneBigWord;		/* TRUE if the variable value is treated as a
   1938 				 * single big word, even if it contains
   1939 				 * embedded spaces (as opposed to the
   1940 				 * usual behaviour of treating it as
   1941 				 * several space-separated words). */
   1942 } ApplyModifiersState;
   1943 
   1944 typedef enum {
   1945     AMR_OK,			/* Continue parsing */
   1946     AMR_UNKNOWN,		/* Not a match, try other modifiers as well */
   1947     AMR_BAD,			/* Error out with "Bad modifier" message */
   1948     AMR_CLEANUP			/* Error out, with "Unfinished modifier"
   1949 				 * if st->missing_delim is set. */
   1950 } ApplyModifierResult;
   1951 
   1952 /* Test whether mod starts with modname, followed by a delimiter. */
   1953 static Boolean
   1954 ModMatch(const char *mod, const char *modname, char endc)
   1955 {
   1956     size_t n = strlen(modname);
   1957     return strncmp(mod, modname, n) == 0 &&
   1958 	   (mod[n] == endc || mod[n] == ':');
   1959 }
   1960 
   1961 /* Test whether mod starts with modname, followed by a delimiter or '='. */
   1962 static inline Boolean
   1963 ModMatchEq(const char *mod, const char *modname, char endc)
   1964 {
   1965     size_t n = strlen(modname);
   1966     return strncmp(mod, modname, n) == 0 &&
   1967 	   (mod[n] == endc || mod[n] == ':' || mod[n] == '=');
   1968 }
   1969 
   1970 /* :@var (at) ...${var}...@ */
   1971 static ApplyModifierResult
   1972 ApplyModifier_Loop(const char **pp, ApplyModifiersState *st)
   1973 {
   1974     ModifyWord_LoopArgs args;
   1975     char delim;
   1976     int prev_sep;
   1977 
   1978     args.ctx = st->ctxt;
   1979 
   1980     (*pp)++;			/* Skip the first '@' */
   1981     delim = '@';
   1982     args.tvar = ParseModifierPart(pp, delim, st->eflags & ~VARE_WANTRES,
   1983 				  st->ctxt, NULL, NULL, NULL);
   1984     if (args.tvar == NULL) {
   1985 	st->missing_delim = delim;
   1986 	return AMR_CLEANUP;
   1987     }
   1988     if (DEBUG(LINT) && strchr(args.tvar, '$') != NULL) {
   1989 	Parse_Error(PARSE_FATAL,
   1990 		    "In the :@ modifier of \"%s\", the variable name \"%s\" "
   1991 		    "must not contain a dollar.",
   1992 		    st->v->name, args.tvar);
   1993 	return AMR_CLEANUP;
   1994     }
   1995 
   1996     args.str = ParseModifierPart(pp, delim, st->eflags & ~VARE_WANTRES,
   1997 				 st->ctxt, NULL, NULL, NULL);
   1998     if (args.str == NULL) {
   1999 	st->missing_delim = delim;
   2000 	return AMR_CLEANUP;
   2001     }
   2002 
   2003     args.eflags = st->eflags & (VARE_UNDEFERR | VARE_WANTRES);
   2004     prev_sep = st->sep;
   2005     st->sep = ' ';		/* XXX: should be st->sep for consistency */
   2006     st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
   2007 			     ModifyWord_Loop, &args);
   2008     st->sep = prev_sep;
   2009     Var_Delete(args.tvar, st->ctxt);
   2010     free(args.tvar);
   2011     free(args.str);
   2012     return AMR_OK;
   2013 }
   2014 
   2015 /* :Ddefined or :Uundefined */
   2016 static ApplyModifierResult
   2017 ApplyModifier_Defined(const char **pp, ApplyModifiersState *st)
   2018 {
   2019     Buffer buf;			/* Buffer for patterns */
   2020     const char *p;
   2021 
   2022     VarEvalFlags eflags = st->eflags & ~VARE_WANTRES;
   2023     if (st->eflags & VARE_WANTRES) {
   2024 	if ((**pp == 'D') == !(st->v->flags & VAR_JUNK))
   2025 	    eflags |= VARE_WANTRES;
   2026     }
   2027 
   2028     /*
   2029      * Pass through mod looking for 1) escaped delimiters,
   2030      * '$'s and backslashes (place the escaped character in
   2031      * uninterpreted) and 2) unescaped $'s that aren't before
   2032      * the delimiter (expand the variable substitution).
   2033      * The result is left in the Buffer buf.
   2034      */
   2035     Buf_Init(&buf, 0);
   2036     p = *pp + 1;
   2037     while (*p != st->endc && *p != ':' && *p != '\0') {
   2038 	if (*p == '\\' &&
   2039 	    (p[1] == ':' || p[1] == '$' || p[1] == st->endc || p[1] == '\\')) {
   2040 	    Buf_AddByte(&buf, p[1]);
   2041 	    p += 2;
   2042 	} else if (*p == '$') {
   2043 	    /*
   2044 	     * If unescaped dollar sign, assume it's a
   2045 	     * variable substitution and recurse.
   2046 	     */
   2047 	    const char *cp2;
   2048 	    int len;
   2049 	    void *freeIt;
   2050 
   2051 	    cp2 = Var_Parse(p, st->ctxt, eflags, &len, &freeIt);
   2052 	    Buf_AddStr(&buf, cp2);
   2053 	    free(freeIt);
   2054 	    p += len;
   2055 	} else {
   2056 	    Buf_AddByte(&buf, *p);
   2057 	    p++;
   2058 	}
   2059     }
   2060     *pp = p;
   2061 
   2062     if (st->v->flags & VAR_JUNK)
   2063 	st->v->flags |= VAR_KEEP;
   2064     if (eflags & VARE_WANTRES) {
   2065 	st->newVal = Buf_Destroy(&buf, FALSE);
   2066     } else {
   2067 	st->newVal = st->val;
   2068 	Buf_Destroy(&buf, TRUE);
   2069     }
   2070     return AMR_OK;
   2071 }
   2072 
   2073 /* :gmtime */
   2074 static ApplyModifierResult
   2075 ApplyModifier_Gmtime(const char **pp, ApplyModifiersState *st)
   2076 {
   2077     time_t utc;
   2078 
   2079     const char *mod = *pp;
   2080     if (!ModMatchEq(mod, "gmtime", st->endc))
   2081 	return AMR_UNKNOWN;
   2082 
   2083     if (mod[6] == '=') {
   2084 	char *ep;
   2085 	utc = strtoul(mod + 7, &ep, 10);
   2086 	*pp = ep;
   2087     } else {
   2088 	utc = 0;
   2089 	*pp = mod + 6;
   2090     }
   2091     st->newVal = VarStrftime(st->val, TRUE, utc);
   2092     return AMR_OK;
   2093 }
   2094 
   2095 /* :localtime */
   2096 static Boolean
   2097 ApplyModifier_Localtime(const char **pp, ApplyModifiersState *st)
   2098 {
   2099     time_t utc;
   2100 
   2101     const char *mod = *pp;
   2102     if (!ModMatchEq(mod, "localtime", st->endc))
   2103 	return AMR_UNKNOWN;
   2104 
   2105     if (mod[9] == '=') {
   2106 	char *ep;
   2107 	utc = strtoul(mod + 10, &ep, 10);
   2108 	*pp = ep;
   2109     } else {
   2110 	utc = 0;
   2111 	*pp = mod + 9;
   2112     }
   2113     st->newVal = VarStrftime(st->val, FALSE, utc);
   2114     return AMR_OK;
   2115 }
   2116 
   2117 /* :hash */
   2118 static ApplyModifierResult
   2119 ApplyModifier_Hash(const char **pp, ApplyModifiersState *st)
   2120 {
   2121     if (!ModMatch(*pp, "hash", st->endc))
   2122 	return AMR_UNKNOWN;
   2123 
   2124     st->newVal = VarHash(st->val);
   2125     *pp += 4;
   2126     return AMR_OK;
   2127 }
   2128 
   2129 /* :P */
   2130 static ApplyModifierResult
   2131 ApplyModifier_Path(const char **pp, ApplyModifiersState *st)
   2132 {
   2133     GNode *gn;
   2134 
   2135     if (st->v->flags & VAR_JUNK)
   2136 	st->v->flags |= VAR_KEEP;
   2137 
   2138     gn = Targ_FindNode(st->v->name, TARG_NOCREATE);
   2139     if (gn == NULL || gn->type & OP_NOPATH) {
   2140 	st->newVal = NULL;
   2141     } else if (gn->path) {
   2142 	st->newVal = bmake_strdup(gn->path);
   2143     } else {
   2144 	st->newVal = Dir_FindFile(st->v->name, Suff_FindPath(gn));
   2145     }
   2146     if (st->newVal == NULL)
   2147 	st->newVal = bmake_strdup(st->v->name);
   2148 
   2149     (*pp)++;
   2150     return AMR_OK;
   2151 }
   2152 
   2153 /* :!cmd! */
   2154 static ApplyModifierResult
   2155 ApplyModifier_Exclam(const char **pp, ApplyModifiersState *st)
   2156 {
   2157     char delim;
   2158     char *cmd;
   2159     const char *errfmt;
   2160 
   2161     (*pp)++;
   2162     delim = '!';
   2163     cmd = ParseModifierPart(pp, delim, st->eflags, st->ctxt,
   2164 			    NULL, NULL, NULL);
   2165     if (cmd == NULL) {
   2166 	st->missing_delim = delim;
   2167 	return AMR_CLEANUP;
   2168     }
   2169 
   2170     errfmt = NULL;
   2171     if (st->eflags & VARE_WANTRES)
   2172 	st->newVal = Cmd_Exec(cmd, &errfmt);
   2173     else
   2174 	st->newVal = varNoError;
   2175     free(cmd);
   2176 
   2177     if (errfmt != NULL)
   2178 	Error(errfmt, st->val);	/* XXX: why still return AMR_OK? */
   2179 
   2180     if (st->v->flags & VAR_JUNK)
   2181 	st->v->flags |= VAR_KEEP;
   2182     return AMR_OK;
   2183 }
   2184 
   2185 /* The :range modifier generates an integer sequence as long as the words.
   2186  * The :range=7 modifier generates an integer sequence from 1 to 7. */
   2187 static ApplyModifierResult
   2188 ApplyModifier_Range(const char **pp, ApplyModifiersState *st)
   2189 {
   2190     int n;
   2191     Buffer buf;
   2192     int i;
   2193 
   2194     const char *mod = *pp;
   2195     if (!ModMatchEq(mod, "range", st->endc))
   2196 	return AMR_UNKNOWN;
   2197 
   2198     if (mod[5] == '=') {
   2199 	char *ep;
   2200 	n = strtoul(mod + 6, &ep, 10);
   2201 	*pp = ep;
   2202     } else {
   2203 	n = 0;
   2204 	*pp = mod + 5;
   2205     }
   2206 
   2207     if (n == 0) {
   2208 	char *as;
   2209 	char **av = brk_string(st->val, &n, FALSE, &as);
   2210 	free(as);
   2211 	free(av);
   2212     }
   2213 
   2214     Buf_Init(&buf, 0);
   2215 
   2216     for (i = 0; i < n; i++) {
   2217 	if (i != 0)
   2218 	    Buf_AddByte(&buf, ' ');	/* XXX: st->sep, for consistency */
   2219 	Buf_AddInt(&buf, 1 + i);
   2220     }
   2221 
   2222     st->newVal = Buf_Destroy(&buf, FALSE);
   2223     return AMR_OK;
   2224 }
   2225 
   2226 /* :Mpattern or :Npattern */
   2227 static ApplyModifierResult
   2228 ApplyModifier_Match(const char **pp, ApplyModifiersState *st)
   2229 {
   2230     const char *mod = *pp;
   2231     Boolean copy = FALSE;	/* pattern should be, or has been, copied */
   2232     Boolean needSubst = FALSE;
   2233     const char *endpat;
   2234     char *pattern;
   2235     ModifyWordsCallback callback;
   2236 
   2237     /*
   2238      * In the loop below, ignore ':' unless we are at (or back to) the
   2239      * original brace level.
   2240      * XXX This will likely not work right if $() and ${} are intermixed.
   2241      */
   2242     int nest = 0;
   2243     const char *p;
   2244     for (p = mod + 1; *p != '\0' && !(*p == ':' && nest == 0); p++) {
   2245 	if (*p == '\\' &&
   2246 	    (p[1] == ':' || p[1] == st->endc || p[1] == st->startc)) {
   2247 	    if (!needSubst)
   2248 		copy = TRUE;
   2249 	    p++;
   2250 	    continue;
   2251 	}
   2252 	if (*p == '$')
   2253 	    needSubst = TRUE;
   2254 	if (*p == '(' || *p == '{')
   2255 	    nest++;
   2256 	if (*p == ')' || *p == '}') {
   2257 	    nest--;
   2258 	    if (nest < 0)
   2259 		break;
   2260 	}
   2261     }
   2262     *pp = p;
   2263     endpat = p;
   2264 
   2265     if (copy) {
   2266 	char *dst;
   2267 	const char *src;
   2268 
   2269 	/* Compress the \:'s out of the pattern. */
   2270 	pattern = bmake_malloc(endpat - (mod + 1) + 1);
   2271 	dst = pattern;
   2272 	src = mod + 1;
   2273 	for (; src < endpat; src++, dst++) {
   2274 	    if (src[0] == '\\' && src + 1 < endpat &&
   2275 		/* XXX: st->startc is missing here; see above */
   2276 		(src[1] == ':' || src[1] == st->endc))
   2277 		src++;
   2278 	    *dst = *src;
   2279 	}
   2280 	*dst = '\0';
   2281 	endpat = dst;
   2282     } else {
   2283 	/*
   2284 	 * Either Var_Subst or ModifyWords will need a
   2285 	 * nul-terminated string soon, so construct one now.
   2286 	 */
   2287 	pattern = bmake_strndup(mod + 1, endpat - (mod + 1));
   2288     }
   2289 
   2290     if (needSubst) {
   2291 	/* pattern contains embedded '$', so use Var_Subst to expand it. */
   2292 	char *old_pattern = pattern;
   2293 	pattern = Var_Subst(pattern, st->ctxt, st->eflags);
   2294 	free(old_pattern);
   2295     }
   2296 
   2297     VAR_DEBUG("Pattern[%s] for [%s] is [%s]\n", st->v->name, st->val, pattern);
   2298 
   2299     callback = mod[0] == 'M' ? ModifyWord_Match : ModifyWord_NoMatch;
   2300     st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
   2301 			     callback, pattern);
   2302     free(pattern);
   2303     return AMR_OK;
   2304 }
   2305 
   2306 /* :S,from,to, */
   2307 static ApplyModifierResult
   2308 ApplyModifier_Subst(const char **pp, ApplyModifiersState *st)
   2309 {
   2310     ModifyWord_SubstArgs args;
   2311     char *lhs, *rhs;
   2312     Boolean oneBigWord;
   2313 
   2314     char delim = (*pp)[1];
   2315     if (delim == '\0') {
   2316 	Error("Missing delimiter for :S modifier");
   2317 	(*pp)++;
   2318 	return AMR_CLEANUP;
   2319     }
   2320 
   2321     *pp += 2;
   2322 
   2323     args.pflags = 0;
   2324 
   2325     /*
   2326      * If pattern begins with '^', it is anchored to the
   2327      * start of the word -- skip over it and flag pattern.
   2328      */
   2329     if (**pp == '^') {
   2330 	args.pflags |= VARP_ANCHOR_START;
   2331 	(*pp)++;
   2332     }
   2333 
   2334     lhs = ParseModifierPart(pp, delim, st->eflags, st->ctxt,
   2335 			    &args.lhsLen, &args.pflags, NULL);
   2336     if (lhs == NULL) {
   2337 	st->missing_delim = delim;
   2338 	return AMR_CLEANUP;
   2339     }
   2340     args.lhs = lhs;
   2341 
   2342     rhs = ParseModifierPart(pp, delim, st->eflags, st->ctxt,
   2343 			    &args.rhsLen, NULL, &args);
   2344     if (rhs == NULL) {
   2345 	st->missing_delim = delim;
   2346 	return AMR_CLEANUP;
   2347     }
   2348     args.rhs = rhs;
   2349 
   2350     oneBigWord = st->oneBigWord;
   2351     for (;; (*pp)++) {
   2352 	switch (**pp) {
   2353 	case 'g':
   2354 	    args.pflags |= VARP_SUB_GLOBAL;
   2355 	    continue;
   2356 	case '1':
   2357 	    args.pflags |= VARP_SUB_ONE;
   2358 	    continue;
   2359 	case 'W':
   2360 	    oneBigWord = TRUE;
   2361 	    continue;
   2362 	}
   2363 	break;
   2364     }
   2365 
   2366     st->newVal = ModifyWords(st->ctxt, st->sep, oneBigWord, st->val,
   2367 			     ModifyWord_Subst, &args);
   2368 
   2369     free(lhs);
   2370     free(rhs);
   2371     return AMR_OK;
   2372 }
   2373 
   2374 #ifndef NO_REGEX
   2375 
   2376 /* :C,from,to, */
   2377 static ApplyModifierResult
   2378 ApplyModifier_Regex(const char **pp, ApplyModifiersState *st)
   2379 {
   2380     char *re;
   2381     ModifyWord_SubstRegexArgs args;
   2382     Boolean oneBigWord;
   2383     int error;
   2384 
   2385     char delim = (*pp)[1];
   2386     if (delim == '\0') {
   2387 	Error("Missing delimiter for :C modifier");
   2388 	(*pp)++;
   2389 	return AMR_CLEANUP;
   2390     }
   2391 
   2392     *pp += 2;
   2393 
   2394     re = ParseModifierPart(pp, delim, st->eflags, st->ctxt, NULL, NULL, NULL);
   2395     if (re == NULL) {
   2396 	st->missing_delim = delim;
   2397 	return AMR_CLEANUP;
   2398     }
   2399 
   2400     args.replace = ParseModifierPart(pp, delim, st->eflags, st->ctxt,
   2401 				     NULL, NULL, NULL);
   2402     if (args.replace == NULL) {
   2403 	free(re);
   2404 	st->missing_delim = delim;
   2405 	return AMR_CLEANUP;
   2406     }
   2407 
   2408     args.pflags = 0;
   2409     oneBigWord = st->oneBigWord;
   2410     for (;; (*pp)++) {
   2411 	switch (**pp) {
   2412 	case 'g':
   2413 	    args.pflags |= VARP_SUB_GLOBAL;
   2414 	    continue;
   2415 	case '1':
   2416 	    args.pflags |= VARP_SUB_ONE;
   2417 	    continue;
   2418 	case 'W':
   2419 	    oneBigWord = TRUE;
   2420 	    continue;
   2421 	}
   2422 	break;
   2423     }
   2424 
   2425     error = regcomp(&args.re, re, REG_EXTENDED);
   2426     free(re);
   2427     if (error) {
   2428 	VarREError(error, &args.re, "Regex compilation error");
   2429 	free(args.replace);
   2430 	return AMR_CLEANUP;
   2431     }
   2432 
   2433     args.nsub = args.re.re_nsub + 1;
   2434     if (args.nsub < 1)
   2435 	args.nsub = 1;
   2436     if (args.nsub > 10)
   2437 	args.nsub = 10;
   2438     st->newVal = ModifyWords(st->ctxt, st->sep, oneBigWord, st->val,
   2439 			     ModifyWord_SubstRegex, &args);
   2440     regfree(&args.re);
   2441     free(args.replace);
   2442     return AMR_OK;
   2443 }
   2444 #endif
   2445 
   2446 static void
   2447 ModifyWord_Copy(const char *word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   2448 {
   2449     SepBuf_AddStr(buf, word);
   2450 }
   2451 
   2452 /* :ts<separator> */
   2453 static ApplyModifierResult
   2454 ApplyModifier_ToSep(const char **pp, ApplyModifiersState *st)
   2455 {
   2456     /* XXX: pp points to the 's', for historic reasons only.
   2457      * Changing this will influence the error messages. */
   2458     const char *sep = *pp + 1;
   2459     if (sep[0] != st->endc && (sep[1] == st->endc || sep[1] == ':')) {
   2460 	/* ":ts<any><endc>" or ":ts<any>:" */
   2461 	st->sep = sep[0];
   2462 	*pp = sep + 1;
   2463     } else if (sep[0] == st->endc || sep[0] == ':') {
   2464 	/* ":ts<endc>" or ":ts:" */
   2465 	st->sep = '\0';		/* no separator */
   2466 	*pp = sep;
   2467     } else if (sep[0] == '\\') {
   2468 	const char *xp = sep + 1;
   2469 	int base = 8;		/* assume octal */
   2470 
   2471 	switch (sep[1]) {
   2472 	case 'n':
   2473 	    st->sep = '\n';
   2474 	    *pp = sep + 2;
   2475 	    break;
   2476 	case 't':
   2477 	    st->sep = '\t';
   2478 	    *pp = sep + 2;
   2479 	    break;
   2480 	case 'x':
   2481 	    base = 16;
   2482 	    xp++;
   2483 	    goto get_numeric;
   2484 	case '0':
   2485 	    base = 0;
   2486 	    goto get_numeric;
   2487 	default:
   2488 	    if (!isdigit((unsigned char)sep[1]))
   2489 		return AMR_BAD;	/* ":ts<backslash><unrecognised>". */
   2490 
   2491 	get_numeric:
   2492 	    {
   2493 		char *end;
   2494 		st->sep = strtoul(xp, &end, base);
   2495 		if (*end != ':' && *end != st->endc)
   2496 		    return AMR_BAD;
   2497 		*pp = end;
   2498 	    }
   2499 	    break;
   2500 	}
   2501     } else {
   2502 	return AMR_BAD;		/* Found ":ts<unrecognised><unrecognised>". */
   2503     }
   2504 
   2505     st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
   2506 			     ModifyWord_Copy, NULL);
   2507     return AMR_OK;
   2508 }
   2509 
   2510 /* :tA, :tu, :tl, :ts<separator>, etc. */
   2511 static ApplyModifierResult
   2512 ApplyModifier_To(const char **pp, ApplyModifiersState *st)
   2513 {
   2514     const char *mod = *pp;
   2515     assert(mod[0] == 't');
   2516 
   2517     *pp = mod + 1;		/* make sure it is set */
   2518     if (mod[1] == st->endc || mod[1] == ':' || mod[1] == '\0')
   2519 	return AMR_BAD;		/* Found ":t<endc>" or ":t:". */
   2520 
   2521     if (mod[1] == 's')
   2522 	return ApplyModifier_ToSep(pp, st);
   2523 
   2524     if (mod[2] != st->endc && mod[2] != ':')
   2525 	return AMR_BAD;		/* Found ":t<unrecognised><unrecognised>". */
   2526 
   2527     /* Check for two-character options: ":tu", ":tl" */
   2528     if (mod[1] == 'A') {	/* absolute path */
   2529 	st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
   2530 				 ModifyWord_Realpath, NULL);
   2531 	*pp = mod + 2;
   2532     } else if (mod[1] == 'u') {
   2533 	size_t i;
   2534 	size_t len = strlen(st->val);
   2535 	st->newVal = bmake_malloc(len + 1);
   2536 	for (i = 0; i < len + 1; i++)
   2537 	    st->newVal[i] = toupper((unsigned char)st->val[i]);
   2538 	*pp = mod + 2;
   2539     } else if (mod[1] == 'l') {
   2540 	size_t i;
   2541 	size_t len = strlen(st->val);
   2542 	st->newVal = bmake_malloc(len + 1);
   2543 	for (i = 0; i < len + 1; i++)
   2544 	    st->newVal[i] = tolower((unsigned char)st->val[i]);
   2545 	*pp = mod + 2;
   2546     } else if (mod[1] == 'W' || mod[1] == 'w') {
   2547 	st->oneBigWord = mod[1] == 'W';
   2548 	st->newVal = st->val;
   2549 	*pp = mod + 2;
   2550     } else {
   2551 	/* Found ":t<unrecognised>:" or ":t<unrecognised><endc>". */
   2552 	return AMR_BAD;
   2553     }
   2554     return AMR_OK;
   2555 }
   2556 
   2557 /* :[#], :[1], etc. */
   2558 static ApplyModifierResult
   2559 ApplyModifier_Words(const char **pp, ApplyModifiersState *st)
   2560 {
   2561     char delim;
   2562     char *estr;
   2563     char *ep;
   2564     int first, last;
   2565 
   2566     (*pp)++;			/* skip the '[' */
   2567     delim = ']';		/* look for closing ']' */
   2568     estr = ParseModifierPart(pp, delim, st->eflags, st->ctxt,
   2569 			     NULL, NULL, NULL);
   2570     if (estr == NULL) {
   2571 	st->missing_delim = delim;
   2572 	return AMR_CLEANUP;
   2573     }
   2574 
   2575     /* now *pp points just after the closing ']' */
   2576     if (**pp != ':' && **pp != st->endc)
   2577 	goto bad_modifier;	/* Found junk after ']' */
   2578 
   2579     if (estr[0] == '\0')
   2580 	goto bad_modifier;	/* empty square brackets in ":[]". */
   2581 
   2582     if (estr[0] == '#' && estr[1] == '\0') { /* Found ":[#]" */
   2583 	if (st->oneBigWord) {
   2584 	    st->newVal = bmake_strdup("1");
   2585 	} else {
   2586 	    Buffer buf;
   2587 
   2588 	    /* XXX: brk_string() is a rather expensive
   2589 	     * way of counting words. */
   2590 	    char *as;
   2591 	    int ac;
   2592 	    char **av = brk_string(st->val, &ac, FALSE, &as);
   2593 	    free(as);
   2594 	    free(av);
   2595 
   2596 	    Buf_Init(&buf, 4);	/* 3 digits + '\0' */
   2597 	    Buf_AddInt(&buf, ac);
   2598 	    st->newVal = Buf_Destroy(&buf, FALSE);
   2599 	}
   2600 	goto ok;
   2601     }
   2602 
   2603     if (estr[0] == '*' && estr[1] == '\0') {
   2604 	/* Found ":[*]" */
   2605 	st->oneBigWord = TRUE;
   2606 	st->newVal = st->val;
   2607 	goto ok;
   2608     }
   2609 
   2610     if (estr[0] == '@' && estr[1] == '\0') {
   2611 	/* Found ":[@]" */
   2612 	st->oneBigWord = FALSE;
   2613 	st->newVal = st->val;
   2614 	goto ok;
   2615     }
   2616 
   2617     /*
   2618      * We expect estr to contain a single integer for :[N], or two integers
   2619      * separated by ".." for :[start..end].
   2620      */
   2621     first = strtol(estr, &ep, 0);
   2622     if (ep == estr)		/* Found junk instead of a number */
   2623 	goto bad_modifier;
   2624 
   2625     if (ep[0] == '\0') {	/* Found only one integer in :[N] */
   2626 	last = first;
   2627     } else if (ep[0] == '.' && ep[1] == '.' && ep[2] != '\0') {
   2628 	/* Expecting another integer after ".." */
   2629 	ep += 2;
   2630 	last = strtol(ep, &ep, 0);
   2631 	if (ep[0] != '\0')	/* Found junk after ".." */
   2632 	    goto bad_modifier;
   2633     } else
   2634 	goto bad_modifier;	/* Found junk instead of ".." */
   2635 
   2636     /*
   2637      * Now seldata is properly filled in, but we still have to check for 0 as
   2638      * a special case.
   2639      */
   2640     if (first == 0 && last == 0) {
   2641 	/* ":[0]" or perhaps ":[0..0]" */
   2642 	st->oneBigWord = TRUE;
   2643 	st->newVal = st->val;
   2644 	goto ok;
   2645     }
   2646 
   2647     /* ":[0..N]" or ":[N..0]" */
   2648     if (first == 0 || last == 0)
   2649 	goto bad_modifier;
   2650 
   2651     /* Normal case: select the words described by seldata. */
   2652     st->newVal = VarSelectWords(st->sep, st->oneBigWord, st->val, first, last);
   2653 
   2654 ok:
   2655     free(estr);
   2656     return AMR_OK;
   2657 
   2658 bad_modifier:
   2659     free(estr);
   2660     return AMR_BAD;
   2661 }
   2662 
   2663 static int
   2664 str_cmp_asc(const void *a, const void *b)
   2665 {
   2666     return strcmp(*(const char * const *)a, *(const char * const *)b);
   2667 }
   2668 
   2669 static int
   2670 str_cmp_desc(const void *a, const void *b)
   2671 {
   2672     return strcmp(*(const char * const *)b, *(const char * const *)a);
   2673 }
   2674 
   2675 /* :O (order ascending) or :Or (order descending) or :Ox (shuffle) */
   2676 static ApplyModifierResult
   2677 ApplyModifier_Order(const char **pp, ApplyModifiersState *st)
   2678 {
   2679     const char *mod = (*pp)++;	/* skip past the 'O' in any case */
   2680 
   2681     char *as;			/* word list memory */
   2682     int ac;
   2683     char **av = brk_string(st->val, &ac, FALSE, &as);
   2684 
   2685     if (mod[1] == st->endc || mod[1] == ':') {
   2686 	/* :O sorts ascending */
   2687 	qsort(av, ac, sizeof(char *), str_cmp_asc);
   2688 
   2689     } else if ((mod[1] == 'r' || mod[1] == 'x') &&
   2690 	       (mod[2] == st->endc || mod[2] == ':')) {
   2691 	(*pp)++;
   2692 
   2693 	if (mod[1] == 'r') {
   2694 	    /* :Or sorts descending */
   2695 	    qsort(av, ac, sizeof(char *), str_cmp_desc);
   2696 
   2697 	} else {
   2698 	    /* :Ox shuffles
   2699 	     *
   2700 	     * We will use [ac..2] range for mod factors. This will produce
   2701 	     * random numbers in [(ac-1)..0] interval, and minimal
   2702 	     * reasonable value for mod factor is 2 (the mod 1 will produce
   2703 	     * 0 with probability 1).
   2704 	     */
   2705 	    int i;
   2706 	    for (i = ac - 1; i > 0; i--) {
   2707 		int rndidx = random() % (i + 1);
   2708 		char *t = av[i];
   2709 		av[i] = av[rndidx];
   2710 		av[rndidx] = t;
   2711 	    }
   2712 	}
   2713     } else {
   2714 	free(as);
   2715 	free(av);
   2716 	return AMR_BAD;
   2717     }
   2718 
   2719     st->newVal = WordList_JoinFree(av, ac, as);
   2720     return AMR_OK;
   2721 }
   2722 
   2723 /* :? then : else */
   2724 static ApplyModifierResult
   2725 ApplyModifier_IfElse(const char **pp, ApplyModifiersState *st)
   2726 {
   2727     char delim;
   2728     char *then_expr, *else_expr;
   2729 
   2730     Boolean value = FALSE;
   2731     VarEvalFlags then_eflags = st->eflags & ~VARE_WANTRES;
   2732     VarEvalFlags else_eflags = st->eflags & ~VARE_WANTRES;
   2733 
   2734     int cond_rc = COND_PARSE;	/* anything other than COND_INVALID */
   2735     if (st->eflags & VARE_WANTRES) {
   2736 	cond_rc = Cond_EvalExpression(NULL, st->v->name, &value, 0, FALSE);
   2737 	if (cond_rc != COND_INVALID && value)
   2738 	    then_eflags |= VARE_WANTRES;
   2739 	if (cond_rc != COND_INVALID && !value)
   2740 	    else_eflags |= VARE_WANTRES;
   2741     }
   2742 
   2743     (*pp)++;			/* skip past the '?' */
   2744     delim = ':';
   2745     then_expr = ParseModifierPart(pp, delim, then_eflags, st->ctxt,
   2746 				  NULL, NULL, NULL);
   2747     if (then_expr == NULL) {
   2748 	st->missing_delim = delim;
   2749 	return AMR_CLEANUP;
   2750     }
   2751 
   2752     delim = st->endc;		/* BRCLOSE or PRCLOSE */
   2753     else_expr = ParseModifierPart(pp, delim, else_eflags, st->ctxt,
   2754 				  NULL, NULL, NULL);
   2755     if (else_expr == NULL) {
   2756 	st->missing_delim = delim;
   2757 	return AMR_CLEANUP;
   2758     }
   2759 
   2760     (*pp)--;
   2761     if (cond_rc == COND_INVALID) {
   2762 	Error("Bad conditional expression `%s' in %s?%s:%s",
   2763 	      st->v->name, st->v->name, then_expr, else_expr);
   2764 	return AMR_CLEANUP;
   2765     }
   2766 
   2767     if (value) {
   2768 	st->newVal = then_expr;
   2769 	free(else_expr);
   2770     } else {
   2771 	st->newVal = else_expr;
   2772 	free(then_expr);
   2773     }
   2774     if (st->v->flags & VAR_JUNK)
   2775 	st->v->flags |= VAR_KEEP;
   2776     return AMR_OK;
   2777 }
   2778 
   2779 /*
   2780  * The ::= modifiers actually assign a value to the variable.
   2781  * Their main purpose is in supporting modifiers of .for loop
   2782  * iterators and other obscure uses.  They always expand to
   2783  * nothing.  In a target rule that would otherwise expand to an
   2784  * empty line they can be preceded with @: to keep make happy.
   2785  * Eg.
   2786  *
   2787  * foo:	.USE
   2788  * .for i in ${.TARGET} ${.TARGET:R}.gz
   2789  * 	@: ${t::=$i}
   2790  *	@echo blah ${t:T}
   2791  * .endfor
   2792  *
   2793  *	  ::=<str>	Assigns <str> as the new value of variable.
   2794  *	  ::?=<str>	Assigns <str> as value of variable if
   2795  *			it was not already set.
   2796  *	  ::+=<str>	Appends <str> to variable.
   2797  *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
   2798  *			variable.
   2799  */
   2800 static ApplyModifierResult
   2801 ApplyModifier_Assign(const char **pp, ApplyModifiersState *st)
   2802 {
   2803     GNode *v_ctxt;
   2804     char *sv_name;
   2805     char delim;
   2806     char *val;
   2807 
   2808     const char *mod = *pp;
   2809     const char *op = mod + 1;
   2810     if (!(op[0] == '=' ||
   2811 	  (op[1] == '=' &&
   2812 	   (op[0] == '!' || op[0] == '+' || op[0] == '?'))))
   2813 	return AMR_UNKNOWN;	/* "::<unrecognised>" */
   2814 
   2815 
   2816     if (st->v->name[0] == 0) {
   2817 	*pp = mod + 1;
   2818 	return AMR_BAD;
   2819     }
   2820 
   2821     v_ctxt = st->ctxt;		/* context where v belongs */
   2822     sv_name = NULL;
   2823     if (st->v->flags & VAR_JUNK) {
   2824 	/*
   2825 	 * We need to bmake_strdup() it in case ParseModifierPart() recurses.
   2826 	 */
   2827 	sv_name = st->v->name;
   2828 	st->v->name = bmake_strdup(st->v->name);
   2829     } else if (st->ctxt != VAR_GLOBAL) {
   2830 	Var *gv = VarFind(st->v->name, st->ctxt, 0);
   2831 	if (gv == NULL)
   2832 	    v_ctxt = VAR_GLOBAL;
   2833 	else
   2834 	    VarFreeEnv(gv, TRUE);
   2835     }
   2836 
   2837     switch (op[0]) {
   2838     case '+':
   2839     case '?':
   2840     case '!':
   2841 	*pp = mod + 3;
   2842 	break;
   2843     default:
   2844 	*pp = mod + 2;
   2845 	break;
   2846     }
   2847 
   2848     delim = st->startc == PROPEN ? PRCLOSE : BRCLOSE;
   2849     val = ParseModifierPart(pp, delim, st->eflags, st->ctxt, NULL, NULL, NULL);
   2850     if (st->v->flags & VAR_JUNK) {
   2851 	/* restore original name */
   2852 	free(st->v->name);
   2853 	st->v->name = sv_name;
   2854     }
   2855     if (val == NULL) {
   2856 	st->missing_delim = delim;
   2857 	return AMR_CLEANUP;
   2858     }
   2859 
   2860     (*pp)--;
   2861 
   2862     if (st->eflags & VARE_WANTRES) {
   2863 	switch (op[0]) {
   2864 	case '+':
   2865 	    Var_Append(st->v->name, val, v_ctxt);
   2866 	    break;
   2867 	case '!': {
   2868 	    const char *errfmt;
   2869 	    char *cmd_output = Cmd_Exec(val, &errfmt);
   2870 	    if (errfmt)
   2871 		Error(errfmt, st->val);
   2872 	    else
   2873 		Var_Set(st->v->name, cmd_output, v_ctxt);
   2874 	    free(cmd_output);
   2875 	    break;
   2876 	}
   2877 	case '?':
   2878 	    if (!(st->v->flags & VAR_JUNK))
   2879 		break;
   2880 	    /* FALLTHROUGH */
   2881 	default:
   2882 	    Var_Set(st->v->name, val, v_ctxt);
   2883 	    break;
   2884 	}
   2885     }
   2886     free(val);
   2887     st->newVal = varNoError;
   2888     return AMR_OK;
   2889 }
   2890 
   2891 /* remember current value */
   2892 static ApplyModifierResult
   2893 ApplyModifier_Remember(const char **pp, ApplyModifiersState *st)
   2894 {
   2895     const char *mod = *pp;
   2896     if (!ModMatchEq(mod, "_", st->endc))
   2897 	return AMR_UNKNOWN;
   2898 
   2899     if (mod[1] == '=') {
   2900 	size_t n = strcspn(mod + 2, ":)}");
   2901 	char *name = bmake_strndup(mod + 2, n);
   2902 	Var_Set(name, st->val, st->ctxt);
   2903 	free(name);
   2904 	*pp = mod + 2 + n;
   2905     } else {
   2906 	Var_Set("_", st->val, st->ctxt);
   2907 	*pp = mod + 1;
   2908     }
   2909     st->newVal = st->val;
   2910     return AMR_OK;
   2911 }
   2912 
   2913 /* Apply the given function to each word of the variable value. */
   2914 static ApplyModifierResult
   2915 ApplyModifier_WordFunc(const char **pp, ApplyModifiersState *st,
   2916 		       ModifyWordsCallback modifyWord)
   2917 {
   2918     char delim = (*pp)[1];
   2919     if (delim != st->endc && delim != ':')
   2920 	return AMR_UNKNOWN;
   2921 
   2922     st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord,
   2923 			    st->val, modifyWord, NULL);
   2924     (*pp)++;
   2925     return AMR_OK;
   2926 }
   2927 
   2928 #ifdef SYSVVARSUB
   2929 /* :from=to */
   2930 static ApplyModifierResult
   2931 ApplyModifier_SysV(const char **pp, ApplyModifiersState *st)
   2932 {
   2933     char delim;
   2934     char *lhs, *rhs;
   2935 
   2936     const char *mod = *pp;
   2937     Boolean eqFound = FALSE;
   2938 
   2939     /*
   2940      * First we make a pass through the string trying
   2941      * to verify it is a SYSV-make-style translation:
   2942      * it must be: <string1>=<string2>)
   2943      */
   2944     int nest = 1;
   2945     const char *next = mod;
   2946     while (*next != '\0' && nest > 0) {
   2947 	if (*next == '=') {
   2948 	    eqFound = TRUE;
   2949 	    /* continue looking for st->endc */
   2950 	} else if (*next == st->endc)
   2951 	    nest--;
   2952 	else if (*next == st->startc)
   2953 	    nest++;
   2954 	if (nest > 0)
   2955 	    next++;
   2956     }
   2957     if (*next != st->endc || !eqFound)
   2958 	return AMR_UNKNOWN;
   2959 
   2960     delim = '=';
   2961     *pp = mod;
   2962     lhs = ParseModifierPart(pp, delim, st->eflags, st->ctxt, NULL, NULL, NULL);
   2963     if (lhs == NULL) {
   2964 	st->missing_delim = delim;
   2965 	return AMR_CLEANUP;
   2966     }
   2967 
   2968     delim = st->endc;
   2969     rhs = ParseModifierPart(pp, delim, st->eflags, st->ctxt, NULL, NULL, NULL);
   2970     if (rhs == NULL) {
   2971 	st->missing_delim = delim;
   2972 	return AMR_CLEANUP;
   2973     }
   2974 
   2975     /*
   2976      * SYSV modifications happen through the whole
   2977      * string. Note the pattern is anchored at the end.
   2978      */
   2979     (*pp)--;
   2980     if (lhs[0] == '\0' && *st->val == '\0') {
   2981 	st->newVal = st->val;	/* special case */
   2982     } else {
   2983 	ModifyWord_SYSVSubstArgs args = {st->ctxt, lhs, rhs};
   2984 	st->newVal = ModifyWords(st->ctxt, st->sep, st->oneBigWord, st->val,
   2985 				 ModifyWord_SYSVSubst, &args);
   2986     }
   2987     free(lhs);
   2988     free(rhs);
   2989     return AMR_OK;
   2990 }
   2991 #endif
   2992 
   2993 /* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
   2994 
   2995 static char *
   2996 ApplyModifiers(
   2997     const char **pp,		/* the parsing position, updated upon return */
   2998     char *val,			/* the current value of the variable */
   2999     char const startc,		/* '(' or '{' or '\0' */
   3000     char const endc,		/* ')' or '}' or '\0' */
   3001     Var * const v,		/* the variable may have its flags changed */
   3002     GNode * const ctxt,		/* for looking up and modifying variables */
   3003     VarEvalFlags const eflags,
   3004     void ** const freePtr	/* free this after using the return value */
   3005 ) {
   3006     ApplyModifiersState st = {
   3007 	startc, endc, v, ctxt, eflags, val,
   3008 	NULL,			/* .newVal */
   3009 	'\0',			/* .missing_delim */
   3010 	' ',			/* .sep */
   3011 	FALSE			/* .oneBigWord */
   3012     };
   3013     const char *p;
   3014     const char *mod;
   3015     ApplyModifierResult res;
   3016 
   3017     assert(startc == '(' || startc == '{' || startc == '\0');
   3018     assert(endc == ')' || endc == '}' || endc == '\0');
   3019 
   3020     p = *pp;
   3021     while (*p != '\0' && *p != endc) {
   3022 
   3023 	if (*p == '$') {
   3024 	    /*
   3025 	     * We may have some complex modifiers in a variable.
   3026 	     */
   3027 	    int rlen;
   3028 	    void *freeIt;
   3029 	    const char *rval = Var_Parse(p, st.ctxt, st.eflags, &rlen, &freeIt);
   3030 
   3031 	    /*
   3032 	     * If we have not parsed up to st.endc or ':',
   3033 	     * we are not interested.
   3034 	     */
   3035 	    int c;
   3036 	    if (rval != NULL && *rval &&
   3037 		(c = p[rlen]) != '\0' && c != ':' && c != st.endc) {
   3038 		free(freeIt);
   3039 		goto apply_mods;
   3040 	    }
   3041 
   3042 	    VAR_DEBUG("Indirect modifier \"%s\" from \"%.*s\"\n", rval, rlen, p);
   3043 
   3044 	    p += rlen;
   3045 
   3046 	    if (rval != NULL && *rval) {
   3047 		const char *rval_pp = rval;
   3048 		st.val = ApplyModifiers(&rval_pp, st.val, 0, 0, v,
   3049 					ctxt, eflags, freePtr);
   3050 		if (st.val == var_Error
   3051 		    || (st.val == varNoError && !(st.eflags & VARE_UNDEFERR))
   3052 		    || *rval_pp != '\0') {
   3053 		    free(freeIt);
   3054 		    goto out;	/* error already reported */
   3055 		}
   3056 	    }
   3057 	    free(freeIt);
   3058 	    if (*p == ':')
   3059 		p++;
   3060 	    else if (*p == '\0' && endc != '\0') {
   3061 		Error("Unclosed variable specification after complex "
   3062 		      "modifier (expecting '%c') for %s", st.endc, st.v->name);
   3063 		goto out;
   3064 	    }
   3065 	    continue;
   3066 	}
   3067     apply_mods:
   3068 	st.newVal = var_Error;	/* default value, in case of errors */
   3069 	res = AMR_BAD;		/* just a safe fallback */
   3070 	mod = p;
   3071 
   3072 	if (DEBUG(VAR)) {
   3073 	    char eflags_str[VarEvalFlags_ToStringSize];
   3074 	    char vflags_str[VarFlags_ToStringSize];
   3075 	    Boolean is_single_char = mod[0] != '\0' &&
   3076 	        (mod[1] == endc || mod[1] == ':');
   3077 
   3078 	    /* At this point, only the first character of the modifier can
   3079 	     * be used since the end of the modifier is not yet known. */
   3080 	    VAR_DEBUG("Applying ${%s:%c%s} to \"%s\" "
   3081 		      "(eflags = %s, vflags = %s)\n",
   3082 		      st.v->name, mod[0], is_single_char ? "" : "...", st.val,
   3083 		      Enum_ToString(eflags_str, sizeof eflags_str, st.eflags,
   3084 				    VarEvalFlags_ToStringSpecs),
   3085 		      Enum_ToString(vflags_str, sizeof vflags_str, st.v->flags,
   3086 				    VarFlags_ToStringSpecs));
   3087 	}
   3088 
   3089 	switch (*mod) {
   3090 	case ':':
   3091 	    res = ApplyModifier_Assign(&p, &st);
   3092 	    break;
   3093 	case '@':
   3094 	    res = ApplyModifier_Loop(&p, &st);
   3095 	    break;
   3096 	case '_':
   3097 	    res = ApplyModifier_Remember(&p, &st);
   3098 	    break;
   3099 	case 'D':
   3100 	case 'U':
   3101 	    res = ApplyModifier_Defined(&p, &st);
   3102 	    break;
   3103 	case 'L':
   3104 	    if (st.v->flags & VAR_JUNK)
   3105 		st.v->flags |= VAR_KEEP;
   3106 	    st.newVal = bmake_strdup(st.v->name);
   3107 	    p++;
   3108 	    res = AMR_OK;
   3109 	    break;
   3110 	case 'P':
   3111 	    res = ApplyModifier_Path(&p, &st);
   3112 	    break;
   3113 	case '!':
   3114 	    res = ApplyModifier_Exclam(&p, &st);
   3115 	    break;
   3116 	case '[':
   3117 	    res = ApplyModifier_Words(&p, &st);
   3118 	    break;
   3119 	case 'g':
   3120 	    res = ApplyModifier_Gmtime(&p, &st);
   3121 	    break;
   3122 	case 'h':
   3123 	    res = ApplyModifier_Hash(&p, &st);
   3124 	    break;
   3125 	case 'l':
   3126 	    res = ApplyModifier_Localtime(&p, &st);
   3127 	    break;
   3128 	case 't':
   3129 	    res = ApplyModifier_To(&p, &st);
   3130 	    break;
   3131 	case 'N':
   3132 	case 'M':
   3133 	    res = ApplyModifier_Match(&p, &st);
   3134 	    break;
   3135 	case 'S':
   3136 	    res = ApplyModifier_Subst(&p, &st);
   3137 	    break;
   3138 	case '?':
   3139 	    res = ApplyModifier_IfElse(&p, &st);
   3140 	    break;
   3141 #ifndef NO_REGEX
   3142 	case 'C':
   3143 	    res = ApplyModifier_Regex(&p, &st);
   3144 	    break;
   3145 #endif
   3146 	case 'q':
   3147 	case 'Q':
   3148 	    if (p[1] == st.endc || p[1] == ':') {
   3149 		st.newVal = VarQuote(st.val, *mod == 'q');
   3150 		p++;
   3151 		res = AMR_OK;
   3152 	    } else
   3153 		res = AMR_UNKNOWN;
   3154 	    break;
   3155 	case 'T':
   3156 	    res = ApplyModifier_WordFunc(&p, &st, ModifyWord_Tail);
   3157 	    break;
   3158 	case 'H':
   3159 	    res = ApplyModifier_WordFunc(&p, &st, ModifyWord_Head);
   3160 	    break;
   3161 	case 'E':
   3162 	    res = ApplyModifier_WordFunc(&p, &st, ModifyWord_Suffix);
   3163 	    break;
   3164 	case 'R':
   3165 	    res = ApplyModifier_WordFunc(&p, &st, ModifyWord_Root);
   3166 	    break;
   3167 	case 'r':
   3168 	    res = ApplyModifier_Range(&p, &st);
   3169 	    break;
   3170 	case 'O':
   3171 	    res = ApplyModifier_Order(&p, &st);
   3172 	    break;
   3173 	case 'u':
   3174 	    if (p[1] == st.endc || p[1] == ':') {
   3175 		st.newVal = VarUniq(st.val);
   3176 		p++;
   3177 		res = AMR_OK;
   3178 	    } else
   3179 		res = AMR_UNKNOWN;
   3180 	    break;
   3181 #ifdef SUNSHCMD
   3182 	case 's':
   3183 	    if (p[1] == 'h' && (p[2] == st.endc || p[2] == ':')) {
   3184 		if (st.eflags & VARE_WANTRES) {
   3185 		    const char *errfmt;
   3186 		    st.newVal = Cmd_Exec(st.val, &errfmt);
   3187 		    if (errfmt)
   3188 			Error(errfmt, st.val);
   3189 		} else
   3190 		    st.newVal = varNoError;
   3191 		p += 2;
   3192 		res = AMR_OK;
   3193 	    } else
   3194 		res = AMR_UNKNOWN;
   3195 	    break;
   3196 #endif
   3197 	default:
   3198 	    res = AMR_UNKNOWN;
   3199 	}
   3200 
   3201 #ifdef SYSVVARSUB
   3202 	if (res == AMR_UNKNOWN) {
   3203 	    assert(p == mod);
   3204 	    res = ApplyModifier_SysV(&p, &st);
   3205 	}
   3206 #endif
   3207 
   3208 	if (res == AMR_UNKNOWN) {
   3209 	    Error("Unknown modifier '%c'", *mod);
   3210 	    for (p++; *p != ':' && *p != st.endc && *p != '\0'; p++)
   3211 		continue;
   3212 	    st.newVal = var_Error;
   3213 	}
   3214 	if (res == AMR_CLEANUP)
   3215 	    goto cleanup;
   3216 	if (res == AMR_BAD)
   3217 	    goto bad_modifier;
   3218 
   3219 	if (DEBUG(VAR)) {
   3220 	    char eflags_str[VarEvalFlags_ToStringSize];
   3221 	    char vflags_str[VarFlags_ToStringSize];
   3222 	    const char *q = st.newVal == var_Error ? "" : "\"";
   3223 	    const char *newVal = st.newVal == var_Error ? "error" : st.newVal;
   3224 
   3225 	    VAR_DEBUG("Result of ${%s:%.*s} is %s%s%s "
   3226 		      "(eflags = %s, vflags = %s)\n",
   3227 		      st.v->name, (int)(p - mod), mod, q, newVal, q,
   3228 		      Enum_ToString(eflags_str, sizeof eflags_str, st.eflags,
   3229 				    VarEvalFlags_ToStringSpecs),
   3230 		      Enum_ToString(vflags_str, sizeof vflags_str, st.v->flags,
   3231 				    VarFlags_ToStringSpecs));
   3232 	}
   3233 
   3234 	if (st.newVal != st.val) {
   3235 	    if (*freePtr) {
   3236 		free(st.val);
   3237 		*freePtr = NULL;
   3238 	    }
   3239 	    st.val = st.newVal;
   3240 	    if (st.val != var_Error && st.val != varNoError) {
   3241 		*freePtr = st.val;
   3242 	    }
   3243 	}
   3244 	if (*p == '\0' && st.endc != '\0') {
   3245 	    Error("Unclosed variable specification (expecting '%c') "
   3246 		  "for \"%s\" (value \"%s\") modifier %c",
   3247 		  st.endc, st.v->name, st.val, *mod);
   3248 	} else if (*p == ':') {
   3249 	    p++;
   3250 	}
   3251 	mod = p;
   3252     }
   3253 out:
   3254     *pp = p;
   3255     return st.val;
   3256 
   3257 bad_modifier:
   3258     Error("Bad modifier `:%.*s' for %s",
   3259 	  (int)strcspn(mod, ":)}"), mod, st.v->name);
   3260 
   3261 cleanup:
   3262     *pp = p;
   3263     if (st.missing_delim != '\0')
   3264 	Error("Unfinished modifier for %s ('%c' missing)",
   3265 	      st.v->name, st.missing_delim);
   3266     free(*freePtr);
   3267     *freePtr = NULL;
   3268     return var_Error;
   3269 }
   3270 
   3271 static Boolean
   3272 VarIsDynamic(GNode *ctxt, const char *varname, size_t namelen)
   3273 {
   3274     if ((namelen == 1 ||
   3275 	 (namelen == 2 && (varname[1] == 'F' || varname[1] == 'D'))) &&
   3276 	(ctxt == VAR_CMD || ctxt == VAR_GLOBAL))
   3277     {
   3278 	/*
   3279 	 * If substituting a local variable in a non-local context,
   3280 	 * assume it's for dynamic source stuff. We have to handle
   3281 	 * this specially and return the longhand for the variable
   3282 	 * with the dollar sign escaped so it makes it back to the
   3283 	 * caller. Only four of the local variables are treated
   3284 	 * specially as they are the only four that will be set
   3285 	 * when dynamic sources are expanded.
   3286 	 */
   3287 	switch (varname[0]) {
   3288 	case '@':
   3289 	case '%':
   3290 	case '*':
   3291 	case '!':
   3292 	    return TRUE;
   3293 	}
   3294 	return FALSE;
   3295     }
   3296 
   3297     if ((namelen == 7 || namelen == 8) && varname[0] == '.' &&
   3298 	isupper((unsigned char)varname[1]) &&
   3299 	(ctxt == VAR_CMD || ctxt == VAR_GLOBAL))
   3300     {
   3301 	return strcmp(varname, ".TARGET") == 0 ||
   3302 	       strcmp(varname, ".ARCHIVE") == 0 ||
   3303 	       strcmp(varname, ".PREFIX") == 0 ||
   3304 	       strcmp(varname, ".MEMBER") == 0;
   3305     }
   3306 
   3307     return FALSE;
   3308 }
   3309 
   3310 /*-
   3311  *-----------------------------------------------------------------------
   3312  * Var_Parse --
   3313  *	Given the start of a variable invocation (such as $v, $(VAR),
   3314  *	${VAR:Mpattern}), extract the variable name, possibly some
   3315  *	modifiers and find its value by applying the modifiers to the
   3316  *	original value.
   3317  *
   3318  * Input:
   3319  *	str		The string to parse
   3320  *	ctxt		The context for the variable
   3321  *	flags		VARE_UNDEFERR	if undefineds are an error
   3322  *			VARE_WANTRES	if we actually want the result
   3323  *			VARE_ASSIGN	if we are in a := assignment
   3324  *	lengthPtr	OUT: The length of the specification
   3325  *	freePtr		OUT: Non-NULL if caller should free *freePtr
   3326  *
   3327  * Results:
   3328  *	The value of the variable expression or var_Error if the
   3329  *	specification is invalid. The length of the specification is
   3330  *	placed in *lengthPtr (for invalid specifications, this is just
   3331  *	2...?).
   3332  *	If *freePtr is non-NULL then it's a pointer that the caller
   3333  *	should pass to free() to free memory used by the result.
   3334  *
   3335  * Side Effects:
   3336  *	Any effects from the modifiers, such as :!cmd! or ::=value.
   3337  *-----------------------------------------------------------------------
   3338  */
   3339 /* coverity[+alloc : arg-*4] */
   3340 const char *
   3341 Var_Parse(const char * const str, GNode *ctxt, VarEvalFlags eflags,
   3342 	  int *lengthPtr, void **freePtr)
   3343 {
   3344     const char	*tstr;		/* Pointer into str */
   3345     Boolean 	 haveModifier;	/* TRUE if have modifiers for the variable */
   3346     char	 startc;	/* Starting character if variable in parens
   3347 				 * or braces */
   3348     char	 endc;		/* Ending character if variable in parens
   3349 				 * or braces */
   3350     Boolean	 dynamic;	/* TRUE if the variable is local and we're
   3351 				 * expanding it in a non-local context. This
   3352 				 * is done to support dynamic sources. The
   3353 				 * result is just the invocation, unaltered */
   3354     const char *extramodifiers;
   3355     Var *v;
   3356     char *nstr;
   3357     char eflags_str[VarEvalFlags_ToStringSize];
   3358 
   3359     VAR_DEBUG("%s: %s with %s\n", __func__, str,
   3360 	      Enum_ToString(eflags_str, sizeof eflags_str, eflags,
   3361 			    VarEvalFlags_ToStringSpecs));
   3362 
   3363     *freePtr = NULL;
   3364     extramodifiers = NULL;	/* extra modifiers to apply first */
   3365     dynamic = FALSE;
   3366 
   3367     startc = str[1];
   3368     if (startc != PROPEN && startc != BROPEN) {
   3369 	char name[2];
   3370 
   3371 	/*
   3372 	 * If it's not bounded by braces of some sort, life is much simpler.
   3373 	 * We just need to check for the first character and return the
   3374 	 * value if it exists.
   3375 	 */
   3376 
   3377 	/* Error out some really stupid names */
   3378 	if (startc == '\0' || strchr(")}:$", startc)) {
   3379 	    *lengthPtr = 1;
   3380 	    return var_Error;
   3381 	}
   3382 
   3383 	name[0] = startc;
   3384 	name[1] = '\0';
   3385 	v = VarFind(name, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   3386 	if (v == NULL) {
   3387 	    *lengthPtr = 2;
   3388 
   3389 	    if (ctxt == VAR_CMD || ctxt == VAR_GLOBAL) {
   3390 		/*
   3391 		 * If substituting a local variable in a non-local context,
   3392 		 * assume it's for dynamic source stuff. We have to handle
   3393 		 * this specially and return the longhand for the variable
   3394 		 * with the dollar sign escaped so it makes it back to the
   3395 		 * caller. Only four of the local variables are treated
   3396 		 * specially as they are the only four that will be set
   3397 		 * when dynamic sources are expanded.
   3398 		 */
   3399 		switch (str[1]) {
   3400 		case '@':
   3401 		    return "$(.TARGET)";
   3402 		case '%':
   3403 		    return "$(.MEMBER)";
   3404 		case '*':
   3405 		    return "$(.PREFIX)";
   3406 		case '!':
   3407 		    return "$(.ARCHIVE)";
   3408 		}
   3409 	    }
   3410 	    return (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
   3411 	} else {
   3412 	    haveModifier = FALSE;
   3413 	    tstr = str + 1;
   3414 	}
   3415     } else {
   3416 	Buffer namebuf;		/* Holds the variable name */
   3417 	int depth;
   3418 	size_t namelen;
   3419 	char *varname;
   3420 
   3421 	endc = startc == PROPEN ? PRCLOSE : BRCLOSE;
   3422 
   3423 	Buf_Init(&namebuf, 0);
   3424 
   3425 	/*
   3426 	 * Skip to the end character or a colon, whichever comes first.
   3427 	 */
   3428 	depth = 1;
   3429 	for (tstr = str + 2; *tstr != '\0'; tstr++) {
   3430 	    /* Track depth so we can spot parse errors. */
   3431 	    if (*tstr == startc)
   3432 		depth++;
   3433 	    if (*tstr == endc) {
   3434 		if (--depth == 0)
   3435 		    break;
   3436 	    }
   3437 	    if (*tstr == ':' && depth == 1)
   3438 		break;
   3439 	    /* A variable inside a variable, expand. */
   3440 	    if (*tstr == '$') {
   3441 		int rlen;
   3442 		void *freeIt;
   3443 		const char *rval = Var_Parse(tstr, ctxt, eflags, &rlen,
   3444 					     &freeIt);
   3445 		if (rval != NULL)
   3446 		    Buf_AddStr(&namebuf, rval);
   3447 		free(freeIt);
   3448 		tstr += rlen - 1;
   3449 	    } else
   3450 		Buf_AddByte(&namebuf, *tstr);
   3451 	}
   3452 	if (*tstr == ':') {
   3453 	    haveModifier = TRUE;
   3454 	} else if (*tstr == endc) {
   3455 	    haveModifier = FALSE;
   3456 	} else {
   3457 	    Parse_Error(PARSE_FATAL, "Unclosed variable \"%s\"",
   3458 			Buf_GetAll(&namebuf, NULL));
   3459 	    /*
   3460 	     * If we never did find the end character, return NULL
   3461 	     * right now, setting the length to be the distance to
   3462 	     * the end of the string, since that's what make does.
   3463 	     */
   3464 	    *lengthPtr = tstr - str;
   3465 	    Buf_Destroy(&namebuf, TRUE);
   3466 	    return var_Error;
   3467 	}
   3468 
   3469 	varname = Buf_GetAll(&namebuf, &namelen);
   3470 
   3471 	/*
   3472 	 * At this point, varname points into newly allocated memory from
   3473 	 * namebuf, containing only the name of the variable.
   3474 	 *
   3475 	 * start and tstr point into the const string that was pointed
   3476 	 * to by the original value of the str parameter.  start points
   3477 	 * to the '$' at the beginning of the string, while tstr points
   3478 	 * to the char just after the end of the variable name -- this
   3479 	 * will be '\0', ':', PRCLOSE, or BRCLOSE.
   3480 	 */
   3481 
   3482 	v = VarFind(varname, ctxt, FIND_ENV | FIND_GLOBAL | FIND_CMD);
   3483 	/*
   3484 	 * Check also for bogus D and F forms of local variables since we're
   3485 	 * in a local context and the name is the right length.
   3486 	 */
   3487 	if (v == NULL && ctxt != VAR_CMD && ctxt != VAR_GLOBAL &&
   3488 	    namelen == 2 && (varname[1] == 'F' || varname[1] == 'D') &&
   3489 	    strchr("@%?*!<>", varname[0]) != NULL)
   3490 	{
   3491 	    /*
   3492 	     * Well, it's local -- go look for it.
   3493 	     */
   3494 	    char name[] = { varname[0], '\0' };
   3495 	    v = VarFind(name, ctxt, 0);
   3496 
   3497 	    if (v != NULL) {
   3498 		if (varname[1] == 'D') {
   3499 		    extramodifiers = "H:";
   3500 		} else { /* F */
   3501 		    extramodifiers = "T:";
   3502 		}
   3503 	    }
   3504 	}
   3505 
   3506 	if (v == NULL) {
   3507 	    dynamic = VarIsDynamic(ctxt, varname, namelen);
   3508 
   3509 	    if (!haveModifier) {
   3510 		/*
   3511 		 * No modifiers -- have specification length so we can return
   3512 		 * now.
   3513 		 */
   3514 		*lengthPtr = tstr - str + 1;
   3515 		if (dynamic) {
   3516 		    char *pstr = bmake_strndup(str, *lengthPtr);
   3517 		    *freePtr = pstr;
   3518 		    Buf_Destroy(&namebuf, TRUE);
   3519 		    return pstr;
   3520 		} else {
   3521 		    Buf_Destroy(&namebuf, TRUE);
   3522 		    return (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
   3523 		}
   3524 	    } else {
   3525 		/*
   3526 		 * Still need to get to the end of the variable specification,
   3527 		 * so kludge up a Var structure for the modifications
   3528 		 */
   3529 		v = bmake_malloc(sizeof(Var));
   3530 		v->name = varname;
   3531 		Buf_Init(&v->val, 1);
   3532 		v->flags = VAR_JUNK;
   3533 		Buf_Destroy(&namebuf, FALSE);
   3534 	    }
   3535 	} else
   3536 	    Buf_Destroy(&namebuf, TRUE);
   3537     }
   3538 
   3539     if (v->flags & VAR_IN_USE) {
   3540 	Fatal("Variable %s is recursive.", v->name);
   3541 	/*NOTREACHED*/
   3542     } else {
   3543 	v->flags |= VAR_IN_USE;
   3544     }
   3545 
   3546     /*
   3547      * Before doing any modification, we have to make sure the value
   3548      * has been fully expanded. If it looks like recursion might be
   3549      * necessary (there's a dollar sign somewhere in the variable's value)
   3550      * we just call Var_Subst to do any other substitutions that are
   3551      * necessary. Note that the value returned by Var_Subst will have
   3552      * been dynamically-allocated, so it will need freeing when we
   3553      * return.
   3554      */
   3555     nstr = Buf_GetAll(&v->val, NULL);
   3556     if (strchr(nstr, '$') != NULL && (eflags & VARE_WANTRES) != 0) {
   3557 	nstr = Var_Subst(nstr, ctxt, eflags);
   3558 	*freePtr = nstr;
   3559     }
   3560 
   3561     v->flags &= ~VAR_IN_USE;
   3562 
   3563     if (nstr != NULL && (haveModifier || extramodifiers != NULL)) {
   3564 	void *extraFree;
   3565 
   3566 	extraFree = NULL;
   3567 	if (extramodifiers != NULL) {
   3568 	    const char *em = extramodifiers;
   3569 	    nstr = ApplyModifiers(&em, nstr, '(', ')',
   3570 				  v, ctxt, eflags, &extraFree);
   3571 	}
   3572 
   3573 	if (haveModifier) {
   3574 	    /* Skip initial colon. */
   3575 	    tstr++;
   3576 
   3577 	    nstr = ApplyModifiers(&tstr, nstr, startc, endc,
   3578 				  v, ctxt, eflags, freePtr);
   3579 	    free(extraFree);
   3580 	} else {
   3581 	    *freePtr = extraFree;
   3582 	}
   3583     }
   3584 
   3585     /* Skip past endc if possible. */
   3586     *lengthPtr = tstr + (*tstr ? 1 : 0) - str;
   3587 
   3588     if (v->flags & VAR_FROM_ENV) {
   3589 	Boolean destroy = nstr != Buf_GetAll(&v->val, NULL);
   3590 	if (!destroy) {
   3591 	    /*
   3592 	     * Returning the value unmodified, so tell the caller to free
   3593 	     * the thing.
   3594 	     */
   3595 	    *freePtr = nstr;
   3596 	}
   3597 	(void)VarFreeEnv(v, destroy);
   3598     } else if (v->flags & VAR_JUNK) {
   3599 	/*
   3600 	 * Perform any freeing needed and set *freePtr to NULL so the caller
   3601 	 * doesn't try to free a static pointer.
   3602 	 * If VAR_KEEP is also set then we want to keep str(?) as is.
   3603 	 */
   3604 	if (!(v->flags & VAR_KEEP)) {
   3605 	    if (*freePtr != NULL) {
   3606 		free(*freePtr);
   3607 		*freePtr = NULL;
   3608 	    }
   3609 	    if (dynamic) {
   3610 		nstr = bmake_strndup(str, *lengthPtr);
   3611 		*freePtr = nstr;
   3612 	    } else {
   3613 		nstr = (eflags & VARE_UNDEFERR) ? var_Error : varNoError;
   3614 	    }
   3615 	}
   3616 	if (nstr != Buf_GetAll(&v->val, NULL))
   3617 	    Buf_Destroy(&v->val, TRUE);
   3618 	free(v->name);
   3619 	free(v);
   3620     }
   3621     return nstr;
   3622 }
   3623 
   3624 /*-
   3625  *-----------------------------------------------------------------------
   3626  * Var_Subst  --
   3627  *	Substitute for all variables in the given string in the given context.
   3628  *	If eflags & VARE_UNDEFERR, Parse_Error will be called when an undefined
   3629  *	variable is encountered.
   3630  *
   3631  * Input:
   3632  *	var		Named variable || NULL for all
   3633  *	str		the string which to substitute
   3634  *	ctxt		the context wherein to find variables
   3635  *	eflags		VARE_UNDEFERR	if undefineds are an error
   3636  *			VARE_WANTRES	if we actually want the result
   3637  *			VARE_ASSIGN	if we are in a := assignment
   3638  *
   3639  * Results:
   3640  *	The resulting string.
   3641  *
   3642  * Side Effects:
   3643  *	Any effects from the modifiers, such as ::=, :sh or !cmd!,
   3644  *	if eflags contains VARE_WANTRES.
   3645  *-----------------------------------------------------------------------
   3646  */
   3647 char *
   3648 Var_Subst(const char *str, GNode *ctxt, VarEvalFlags eflags)
   3649 {
   3650     Buffer buf;			/* Buffer for forming things */
   3651     Boolean trailingBslash;
   3652 
   3653     /* Set true if an error has already been reported,
   3654      * to prevent a plethora of messages when recursing */
   3655     static Boolean errorReported;
   3656 
   3657     Buf_Init(&buf, 0);
   3658     errorReported = FALSE;
   3659     trailingBslash = FALSE;	/* variable ends in \ */
   3660 
   3661     while (*str) {
   3662 	if (*str == '\n' && trailingBslash)
   3663 	    Buf_AddByte(&buf, ' ');
   3664 
   3665 	if (*str == '$' && str[1] == '$') {
   3666 	    /*
   3667 	     * A dollar sign may be escaped with another dollar sign.
   3668 	     * In such a case, we skip over the escape character and store the
   3669 	     * dollar sign into the buffer directly.
   3670 	     */
   3671 	    if (save_dollars && (eflags & VARE_ASSIGN))
   3672 		Buf_AddByte(&buf, '$');
   3673 	    Buf_AddByte(&buf, '$');
   3674 	    str += 2;
   3675 	} else if (*str != '$') {
   3676 	    /*
   3677 	     * Skip as many characters as possible -- either to the end of
   3678 	     * the string or to the next dollar sign (variable invocation).
   3679 	     */
   3680 	    const char *cp;
   3681 
   3682 	    for (cp = str++; *str != '$' && *str != '\0'; str++)
   3683 		continue;
   3684 	    Buf_AddBytesBetween(&buf, cp, str);
   3685 	} else {
   3686 	    int length;
   3687 	    void *freeIt;
   3688 	    const char *val = Var_Parse(str, ctxt, eflags, &length, &freeIt);
   3689 
   3690 	    /*
   3691 	     * When we come down here, val should either point to the
   3692 	     * value of this variable, suitably modified, or be NULL.
   3693 	     * Length should be the total length of the potential
   3694 	     * variable invocation (from $ to end character...)
   3695 	     */
   3696 	    if (val == var_Error || val == varNoError) {
   3697 		/*
   3698 		 * If performing old-time variable substitution, skip over
   3699 		 * the variable and continue with the substitution. Otherwise,
   3700 		 * store the dollar sign and advance str so we continue with
   3701 		 * the string...
   3702 		 */
   3703 		if (oldVars) {
   3704 		    str += length;
   3705 		} else if ((eflags & VARE_UNDEFERR) || val == var_Error) {
   3706 		    /*
   3707 		     * If variable is undefined, complain and skip the
   3708 		     * variable. The complaint will stop us from doing anything
   3709 		     * when the file is parsed.
   3710 		     */
   3711 		    if (!errorReported) {
   3712 			Parse_Error(PARSE_FATAL, "Undefined variable \"%.*s\"",
   3713 				    length, str);
   3714 		    }
   3715 		    str += length;
   3716 		    errorReported = TRUE;
   3717 		} else {
   3718 		    Buf_AddByte(&buf, *str);
   3719 		    str += 1;
   3720 		}
   3721 	    } else {
   3722 		size_t val_len;
   3723 
   3724 		str += length;
   3725 
   3726 		val_len = strlen(val);
   3727 		Buf_AddBytes(&buf, val, val_len);
   3728 		trailingBslash = val_len > 0 && val[val_len - 1] == '\\';
   3729 	    }
   3730 	    free(freeIt);
   3731 	    freeIt = NULL;
   3732 	}
   3733     }
   3734 
   3735     return Buf_DestroyCompact(&buf);
   3736 }
   3737 
   3738 /* Initialize the module. */
   3739 void
   3740 Var_Init(void)
   3741 {
   3742     VAR_INTERNAL = Targ_NewGN("Internal");
   3743     VAR_GLOBAL = Targ_NewGN("Global");
   3744     VAR_CMD = Targ_NewGN("Command");
   3745 }
   3746 
   3747 
   3748 void
   3749 Var_End(void)
   3750 {
   3751     Var_Stats();
   3752 }
   3753 
   3754 void
   3755 Var_Stats(void)
   3756 {
   3757     Hash_DebugStats(&VAR_GLOBAL->context, "VAR_GLOBAL");
   3758 }
   3759 
   3760 
   3761 /****************** PRINT DEBUGGING INFO *****************/
   3762 static void
   3763 VarPrintVar(void *vp, void *data MAKE_ATTR_UNUSED)
   3764 {
   3765     Var *v = (Var *)vp;
   3766     fprintf(debug_file, "%-16s = %s\n", v->name, Buf_GetAll(&v->val, NULL));
   3767 }
   3768 
   3769 /* Print all variables in a context, unordered. */
   3770 void
   3771 Var_Dump(GNode *ctxt)
   3772 {
   3773     Hash_ForEach(&ctxt->context, VarPrintVar, NULL);
   3774 }
   3775