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