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