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