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