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