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