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