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