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